[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

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/