I decided to see the difference in the processing speed of the for and for-each cycles.
long start,end = 0; start = System.currentTimeMillis(); ArrayList<Long> al = new ArrayList<>(); for(long a = 0; a < 10000000; a++) { al.add(a);} System.out.println("ArrayList size = "+ al.size()); for(long b : al){end = System.currentTimeMillis();} System.out.println("Выполнение for-each = " + (end-start)+" mc"); start = System.currentTimeMillis(); for(long a = 0; a < al.size(); a++) { end = System.currentTimeMillis(); } System.out.println("Стандартный цикл = " + (end-start)+" mc"); Tolley, I wrote something wrong or the speed is really very different. Got on exit:
ArrayList size = 10000000 Выполнение for-each = 10616 mc Стандартный цикл = 475 mc The numbers are understandably different, but the difference between them is always almost three times.
Therefore, I want to know, it turns out that the classical cycle works three times faster or made a mistake in the program?
Even if you remake it like this:
start = System.currentTimeMillis(); for(long b : al); end = System.currentTimeMillis(); System.out.println("Выполнение for-each = " + (end-start)+" mc"); start = System.currentTimeMillis(); for(long a = 0; a < al.size(); a++); end = System.currentTimeMillis(); The difference still turns out big.
startcaptures the filling of an array as for afor-eachloop. - Alex Krassstartvalues occurs - Sergeyforeach, by the way, works through an iterator.for(Iterator<Long> i = a1.iterator(); i.hasNext(); ) { ... }- Sergey