Here are my test for two equals methods:
Random generator = new Random();
long startTime = System.nanoTime();
for(int i = 0; i<1000; i++) {
Integer int11 = generator.nextInt(1000);
Integer int22 = generator.nextInt(1000);
int11.equals(int22);
}
long endTime = System.nanoTime();
long duration = (endTime - startTime);
System.out.println(duration + " ns");
Random generator1 = new Random();
long startTime1 = System.nanoTime();
for(int i = 0; i<1000; i++) {
Integer int1 = generator1.nextInt(1000);
Integer int2 = generator1.nextInt(1000);
Objects.equals(int1, int2);
}
long endTime1 = System.nanoTime();
long duration1 = (endTime1 - startTime1);
System.out.println(duration1 + " ns");
I just wanted to know, how much slower is the Objects.equals() method, but I got following output:
1005750 ns
650554 ns
When I replaced these two methods:
Random generator1 = new Random();
long startTime1 = System.nanoTime();
for(int i = 0; i<1000; i++) {
Integer int1 = generator1.nextInt(1000);
Integer int2 = generator1.nextInt(1000);
Objects.equals(int1, int2);
}
long endTime1 = System.nanoTime();
long duration1 = (endTime1 - startTime1);
System.out.println(duration1 + " ns");
Random generator = new Random();
long startTime = System.nanoTime();
for(int i = 0; i<1000; i++) {
Integer int11 = generator.nextInt(1000);
Integer int22 = generator.nextInt(1000);
int11.equals(int22);
}
long endTime = System.nanoTime();
long duration = (endTime - startTime);
System.out.println(duration + " ns");
I get very similar output to the previous one:
1026871 ns
614074 ns
So, my question is: Why does the second "test" execute much faster than the first one in both cases? What does it depend on?