2

I am currently testing in Java whether the use of a custom class or int arrays as a datatype is faster and ran speed tests for that purpose (see below).

int repetitions = 1000000000;

for (int i = 0; i < repetitions*10; i++) {
    Move move3 = new Move(2, 3);
    int sum3 = move3.x + move3.y;
}

// object block
long start = System.nanoTime();
for (int i = 0; i < repetitions; i++) {
    Move move2 = new Move(2, 3);
    int sum2 = move2.x + move2.y;
}
System.out.println("Object took " + (System.nanoTime() - start) + "ns");

// array block
long start2 = System.nanoTime();
for (int i = 0; i < repetitions; i++) {
    int[] move = new int[]{2, 3};
    int sum = move[0] + move[1];
}
System.out.println("Array took " + (System.nanoTime() - start2) + "ns");

Swapping around the timing blocks basically decides what is faster. This was by a factor of 4 originally, but running the meaningless first block beforehand reduced it to a factor of about 1.1. Why is this? Is there a "warmup period" for the JVM? And how could I get completely rid of the issue?

(I know, I can get all performance-related information from the fact that swapping changes the advantage, but I am curious what is happening here.)

weidler
  • 676
  • 1
  • 6
  • 22
  • the first block might affect your comparison for you allocates a lot of memory for by creating new object inside the loop... I changed your repetitions variable to 2000000000 and the factor becomes around 1.1 (without the first block), you can try not to create any object in your first block... – wenzi Oct 23 '18 at 14:33
  • @wenzi more repetitions and removing the first block doesnt change much, its still a factor of around 2-3. Maybe its a hardware dependent issue? I even ran it Integer.MAX_VALUE times and it still is a factor of 1.8 – weidler Oct 23 '18 at 14:44
  • If I use Integer.MAX_VALUE, this is the closest result: Object took 1495768764ns Array took 1463381341ns (without first block) – wenzi Oct 23 '18 at 15:15
  • Ok, no clue why it is different for me but thanks for confirming that there is actually no real time difference! – weidler Oct 23 '18 at 17:02
  • sure... the array seems to be a little more efficient... maybe you could try clean up your project or restart jvm? not an expert on this but this post is interesting – wenzi Oct 23 '18 at 17:12
  • I suppose, the linked question help. Put simply: Use [JMH](http://openjdk.java.net/projects/code-tools/jmh/). Bachmarking Java is too hard, that's why we've got JMH. – maaartinus Oct 24 '18 at 10:20

1 Answers1

0

There is actually the warm up for the JVM. Try to look here.

NikNik
  • 2,191
  • 2
  • 15
  • 34