[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
RE: Style question
The reason for the increased performance when declaring the size variable
prior to the loop is that the time to call a method is about 2 to 3 times
greater than the time to get a local variable.
I like to try to limit the scope of my variables for style and simplicity.
My view is that when someone else or even myself looks at the code at a
later time, there is less to keep track of if the scope is limited. Also,
this helps with garbage collection. The less time an object is referenced,
the more likely it is to be garbage collected when it runs.
I would rewrite your third test:
for (int j = 0, sz = v.size(); j < sz; ++j) {
Integer i = (Integer) v.elementAt(j);
}
and if the synchronization of the Vector is not neccessary in the loop
Integer[] intArray = (Integer[])v.toArray(intArray);
for(int j=0, sz=intArray.length; j < sz; j++) {
Integer i = intArray[j];
}
-----Original Message-----
From: Michael Campbell [mailto:michael_s_campbell@yahoo.com]
Sent: Friday, November 01, 2002 5:49 PM
To: ajug-members@ajug.org
Subject: re: Style question
I think the "style question" thread turned into more of a performance
thread, which may or may not have been what the original poster was
getting at (I suspect the question was more related to "Do you
declare variables where first used, or earlier?"), but perhaps not.
Anyway, in keeping with the performance theme, I ran a quick test.
"v" here is a vector of 3,000,000 Integer objects.
Loop1:
Integer i = null;
for (int j = 0; j < v.size(); ++j) {
i = (Integer) v.elementAt(j);
}
Loop2:
for (int j = 0; j < v.size(); ++j) {
Integer i = (Integer) v.elementAt(j);
}
I ran each loop, surrounded by calls to System.currentTimeMillis(),
50 times.
The average time for the 2 tests were generally within 5 milliseconds
of each other (total 155ms; so about a 3% difference).
The tests were run in 1-2-3-1-2-3-1-2-3... order, NOT
1-1-1-...-2-2-2-...-3-3-3-... order to minimize external factors from
overly affecting one test vs another.
In short, I think the difference in time is extremely negligible, and
is probably well within statistical "noise" levels.
As the "pre-calculate the size() call" seemed a valid optimization, I
did that as test 3. The average time for that was about 113ms (vs
the 152ms for the others), so about a 25% reduction in time there.
The code for that is:
int sz = v.size();
Integer i = null;
for (int j = 0; j < sz; ++j) {
i = (Integer) v.elementAt(j);
}
=====
--
Yahoo IM: michael_s_campbell
__________________________________________________
Do you Yahoo!?
HotJobs - Search new jobs daily now
http://hotjobs.yahoo.com/