When executed once, code 1 is faster than code 2. The difference is quite significant.
But, when these codes are executed inside for loop (50 million times, see code 1 inside for loop and code 2 inside for loop) code 1 has the worst performance.
Is it possible to make code 1 perform better inside for loop?
Another question: is there another way to do these calculations inside for loop with a better performance?
int [] arr1 = new int[50000000];
for (int i = 0; i < 50000000; i++) {
arr1[i] = i + 1000;
}
//code 1:
long startTime1 = System.nanoTime();
int som1 = 426;
double a1 = (double) ((((double) Math.round((double) Math.pow((double) arr1[arr1.length - 1] / (double) som1, 2)) - 1) / 50 % 1) * 50) + 1;
int a2 = (int) Math.round(a1);
long estimatedTime1 = System.nanoTime() - startTime1;
System.out.println("Code 1: " + estimatedTime1);
//code 2:
long startTime2 = System.nanoTime();
int som2 = 426;
double a3 = (double) arr1[arr1.length - 1] / (double) som2;
double a4 = (double) (Math.round(a3 * a3) - 1);
double a5 = (double) a4 / 50;
double a6 = (double) Math.floor(a5);
double a7 = (double) ((a5 - a6) * 50) + 1;
int a8 = (int) Math.round(a7);
long estimatedTime2 = System.nanoTime() - startTime2;
System.out.println("Code 2: " + estimatedTime2);
//code 1 inside for loop:
long startTime3 = System.nanoTime();
int som3 = 426;
for (int j1 = 0; j1 < arr1.length; j1++) {
double a9 = (double) ((((double) Math.round((double) Math.pow((double) arr1[j1] / (double) som1, 2)) - 1) / 50 % 1) * 50) + 1;
int a10 = (int) Math.round(a9);
}
long estimatedTime3 = System.nanoTime() - startTime3;
System.out.println("Code 1 inside for loop: " + estimatedTime3);
//code 2 inside for loop:
long startTime4 = System.nanoTime();
int som4 = 426;
for (int j2 = 0; j2 < arr1.length; j2++) {
double a11 = (double) arr1[j2] / (double) som4;
double a12 = (double) (Math.round(a11 * a11) - 1);
double a13 = (double) a12 / 50;
double a14 = (double) Math.floor(a13);
double a15 = (double) ((a13 - a14) * 50) + 1;
int a16 = (int) Math.round(a15);
}
long estimatedTime4 = System.nanoTime() - startTime4;
System.out.println("Code 2 inside for loop: " + estimatedTime4);
Edit : As explained by @Sweeper, code 1 is slower in both cases. As I am trying to improve the performance of this code inside for loop, I would like to ask if there is a faster way to do these calculations inside for loop.