Friends, I can not understand the reason for the long work cycle. So, I create a cycle.

for (int i = 1; i < Integer.MAX_VALUE; i++) { // Вычисляем количество цифр в числе i int length = (int)Math.ceil(Math.log10(i)); } 

The whole program works like this 10ms and ends successfully. Such a program works 3ms:

 for (int i = 1; i < Integer.MAX_VALUE; i++) { // Создаем массив длиной 10 (количество цифр в Integer.MAX_VALUE) int[] digits = new int[10]; } 

But this program hangs for a long time:

 for (int i = 1; i < Integer.MAX_VALUE; i++) { int length = (int)Math.ceil(Math.log10(i)); int[] digits = new int[length]; } 

Why? After all, the value of length will always be less than or equal to 10. And I can not understand. After all, this program works only 12ms:

 for (int i = 1; i < Integer.MAX_VALUE; i++) { int length = (int)Math.ceil(Math.log10(i)); int[] digits = new int[10]; } 
  • What version of java is used? I have the same picture on 1.7_40, and on the new 1.8_77 any Math.ceil call is not optimized at all (you can not even create an array). If Math.ceil replaced by a caste to int , then everything ends successfully. - zRrr

1 answer 1

In the first two examples, the calculated value is not used anywhere, so the optimizer simply deletes the entire cycle, as if it does not exist.

But the example where the calculated value is used to create an array works for real. That is, with the speed with which computing power is capable.

  • for (int i = 1; i < Integer.MAX_VALUE; i++) { int length = (int)Math.ceil(Math.log10(i)); int[] digits = new int[20]; digits[0] = length; } for (int i = 1; i < Integer.MAX_VALUE; i++) { int length = (int)Math.ceil(Math.log10(i)); int[] digits = new int[20]; digits[0] = length; } 13ms - valentinburk
  • Calculate the frequency of the processor in Hertz. 1 / (0.013 / 2 ** 31) = 165191049846.15 - 165 GHz. Excellent percent. - Vanyamba Electronics
  • Maybe I don’t understand something .. picshare.ru/uploads/160403/5m9RDws842.jpg - valentinburk
  • I would be grateful if you indicated what I was doing wrong - valentinburk
  • Please measure the cycle time. for (int i = 1; i <1000; i ++) {int length = (int) Math.ceil (Math.log10 (i)); int [] digits = new int [length]; } - Vanyamba Electronics