commons-dev mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Henri Yandell <flame...@gmail.com>
Subject [lang] Findbugs, performance, fun
Date Sun, 15 Mar 2009 10:45:04 GMT
Findbugs claims we should be writing Integer.valueOf not new Integer
as it's guaranteed to be faster. The same for the other primitive
wrappers. I can't let such a statement of surety go untested, so I had
a play and used the following as a test:

public class Perf {

    public static void main(String[] args) throws Exception {
        int count = Integer.parseInt(args[0]);
        for(int i=0; i<100; i++) {
            System.out.println("Valueof faster: " + test(count));
        }
    }

    public static boolean test(int count) {
        int step = count / 2;

        long ln = System.nanoTime();
        testIntCache(step);
        testIntCache(step);
        ln = (System.nanoTime() - ln)/1000;
        System.out.println("Time for " + count + " valueOf Int: " + ln);

        long ln2 = System.nanoTime();
        testIntCreate(step);
        testIntCreate(step);
        ln2 = (System.nanoTime() - ln2)/1000;
        System.out.println("Time for " + count + " new Int: " + ln2);

        return ln < ln2;

    }

    public static void testIntCache(int count) {
        Integer in = null;
        for(int i=0; i<count; i++) {
            in = Integer.valueOf(i);
        }
    }

    public static void testIntCreate(int count) {
        Integer in = null;
        for(int i=0; i<count; i++) {
            in = new Integer(i);
        }
    }

}

I found on the Apple JVM 1.5.0_16 that valueOf is faster when:

count = 100 -> Faster about 94% of the time.
count = 1000 -> Faster about 89% of the time.
count = 10000 -> Faster about 32% of the time.
count = 100000 -> Faster about 3% of the time.

valueOf is always much slower for the first loop (building cache
presumably). Also often much slower on the third loop too. Weird.
new Int is always much slower on the fourth loop - more so for smaller
counts. Maybe JIT happening, interesting that it would JIT more for
new than valueOf if that's the case.

Ideally I should discard these first four loops, but it wouldn't
change the above too much.

Anyway... amusing play stuff when I should be sleeping; and not
believing FindBugs too much. Need to try for Double, Long etc; maybe
this lore holds more true there. Plus maybe it's Apple's JVM being
interesting and this holds true in Sun land.

Hen

---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscribe@commons.apache.org
For additional commands, e-mail: dev-help@commons.apache.org


Mime
View raw message