Re: slow as molasses
On 10/4/11 2:16 AM, bob wrote:
So, I wrote some code, but it is slow as molasses. Any easy ways to
speed this up?
float[] getVertices(String filename) {
try {
AssetManager am = this.getResources().getAssets();
InputStream is = am.open(filename);
Scanner s = new Scanner(is);
long numfloats = s.nextLong();
float[] f = new float[(int) numfloats];
for (int ctr = 0; ctr< f.length; ctr++) {
f[ctr] = s.nextFloat();
}
return f;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
Yes, the fastest way to make something faster is to figure out exactly
what is slow in the first place.
What you have posted here doesn't work at all, so there is no way to
speed it up. You will need to provide an SSCCE (see
<http://sscce.org/>) in order for us to provide the support you need.
For instance, we don't know if it is "getResources()" that is slow, or
getAsstes() that is slow; maybe am.open(filename) is slow. Maybe its
not actually getVertices that is slow but some code before or after it.
There is a common type of tool used for figuring out what is slow. That
tool is called a Profiler. There are plenty of good profilers for Java,
though they range in price and features. I seem to recall there was a
free eclipse based one (which didn't have every feature I needed, but
might help in this case).
The other important thing to remember is to set a "goal" speed. "As
fast as possible" isn't a good metric. It's better to set a speed and
know when you're done optimizing, than to just say "This is too slow".
So, now that I've gotten all my disclosures and pedagogical urges
satisfied, I would suspect Andreas' advice, to add wrap is with a
BufferedInputStream, is probably the solution. If, indeed, the problem
is the speed of reading from that stream.
Hope this helps,
Daniel.