I am developing an app where time-cost of an algorithm matters a lot.
In the algorithm, I need to get path string to a file in assets folder. And I got answer from this question.
The file is a configuration file, which is ~400 bytes in size. The library I used requires path, but not some Java string.
My code is like:
public static File getCacheFile(String path, Context context) throws IOException {
File cacheFile = new File(context.getCacheDir(), path);
try {
InputStream inputStream = context.getAssets().open(path);
try {
FileOutputStream outputStream = new FileOutputStream(cacheFile);
try {
byte[] buf = new byte[1024];
int len;
while ((len = inputStream.read(buf)) > 0) {
outputStream.write(buf, 0, len);
}
} finally {
outputStream.close();
}
} finally {
inputStream.close();
}
} catch (IOException e) {
throw new IOException("Could not open file", e);
}
return cacheFile;
}
If I run the algorithm for the first time since I start my app, it will cost ~900ms.
If I run the algorithm again without restarting the app, it will cost ~400ms.
So I guess the time difference is that this function attempts to load the file into cache and read path from the cache? Maybe the file is already in the cache and that is why it is faster.
Is there any way to make it faster? E.g. preload this file to cache in onCreate()
, maybe?
Edit: I tried to preload this file in onCreate()
and it does not work.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
getCacheFile("a.properties", getApplicationContext());
} catch (IOException e) {
e.printStackTrace();
}
}
Edit2: Not sure whether it matters, but my algorithm is posted here.