D
D
Daniel2018-03-15 12:59:18
Java
Daniel, 2018-03-15 12:59:18

Why is the standard filling of an int array several times slower than using an Object[] array?

Now I'm studying compilers and then I started to arrange simple experiments and found that a seemingly more complicated way works many times faster?
Why is this code, with declaring an array, 1-10 times faster, and the fill rate is
O(α(n)) while the most standard way is O(a(n)*log(n)) which is much more?

//За 40-60 мс
   List s=new ArrayList(a);
   int i=0;
   for(Object p : s){
         p=i++;     
        }

And this one is slower at a = 40 999 999 250 -600 ms
int i2[]=new int[a];
       
 for(i=0;i<a;i++){
           i2[i]=i;

At the same time, I combined and swapped tests, did both before and after, so that nothing would be cached.
It's all about for( el : list) , but I twist the same i++ in a loop, and the same check goes there (probably) . The question is purely about the work of the compiler itself, the stack of functions, while all operations will also be faster, even taking into account the conversion from an object to int

Answer the question

In order to leave comments, you need to log in

1 answer(s)
G
GavriKos, 2018-03-15
@GavriKos

a is an int?
Then in the first case, the array will be empty, and accordingly the loop will never be executed at all.
And in the second case, it will be executed a times.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question