Local Variables
A few years ago a colleague criticized some code I wrote for local variable inefficiency. Here’s an example of what he did not like:
for (int i = 0; i < 10; i++) { String s = String.valueOf(i); }
He said that Java allocated 10 Strings when that code ran. A better way was this:
String s; for (int i = 0; i < 10; i++) { s = String.valueOf(i); }
So that’s the way I’ve been writing Java code for years now, thinking I am being super efficient.
Well, joke’s on me. Today I found this blog post and learned that his assumption is completely incorrect. The first way above is better because it makes the code more readable and prevents possible variable scoping problems.
Comments (0)
Trackbacks (0)
Leave a comment
Trackback