tags:

views:

108

answers:

1

I need to pass an x/y around. I was just using java.awt.Point. I do this a lot considering it's the nature of the app, but tons slower then normal arrays. I also tried to create my own "FastPoint" which is just an int x/y and very simple class constructor, that's really slow too.

Time is in millescond.

java.awt.Point: 10374
FastPoint: 10032
Arrays: 1210

public class FastPoint {  

    public int x;  
    public int y;  

    public FastPoint(int x, int y) {  
            this.x = x;  
            this.y = y;  
    }
}

Jvisualvm says Point (either awt or my own) are using tons of memory compared to simple int[] array.

I guess that's just overhead from having to create an object instead of a um, basic type? Any way to tweak or optimize this Point class? I've already switched to basic int arrays (which is tons faster now), but just trying to understand why this is slow and if there is anything I can do about it?

Test Code:

for (int i = 0; i < maxRuns; i++) { 
    point = new Point(i,i); 
}

for (int i = 0; i < maxRuns; i++) { 
    a[0] = i; a[1] = i; 
}
+9  A: 

Your test harness is biased: You create a new point in each iteration, but create the array just once. If you move the array allocation into the loop, the difference is not as big, and arrays are actually slightly slower:

Point: 19 nano seconds / iteration

Array: 47 nano seconds / iteration

This is as expected, since array accesses need to perform bounds checking, but field assignment doesn't (the JIT has apparently inlined the point constructor).

Also note that instrumenting a virtual machine for cpu profiling incurs additional overhead, which can - in some cases drastically - change the performance behaviour of the application under test.

meriton