Reading text files is damn slow on Android!
In a Android application I wanted to use Scanner class to read a list of floats from a text file (it’s a list of vertex coordinates for OpenGL). Exact code is:
Scanner in = new Scanner(new BufferedInputStream(getAssets().open("vertexes.off"))); final float vertexes = new float[nrVertexes]; for(int i=0;i vertexes[i] = in.nextFloat(); }
It seems however that this is incredibly slow (it took 30 minutes to read 10,000 floats!) – as tested on the 2.1 emulator. Run on an actual device this is a bit faster but still very slow – order of minutes. On a PC Java application it takes 1 second to read 20,000 floats (with the same code). I profiled it (for 100 floats) and it seems that the calls to nextFloat take all the time. Because of the BufferedInputStream only 2 calls are made to read from the input and they take very little time (35ms/call). However calls to nextFloat take 435ms/call which is huge. By looking at children calls it seems that calls inside NumberFormat and Pattern are the killers. There are a lot of memory allocations and the Android VM and GC doesn’t seem to be as optimized as the PC one.
As a solution I found the following to work very well: first I parse my input file on the PC and transform it into binary data, then I read it on the device byte by byte (buffered) and reconstruct the numbers. This is MUCH faster. It takes 1.5s to read 20,000 floats. I say it’s a enormous improvement from 1 hour
Have a look at this StackOverflow discussion for more ideas.