I’m trying to figure out , why compiler looks through the collection using functional style swiftly then imperative. Here is the simple example where functional search goes first and takes 9.5 sec to deal with it , while imperative follows right behind with 10.3. As soon as I rearrange them , and put imperative before functional, results become similar: 10.1 and 10.29
I’ve added some changes based on users responses , which make my code more correct. Now benchmark starts in right moment of time and count time of what I exactly need. But question remains unanswered. Even though I run two independent timers, for every loop, Functional loop complete it’s search much faster then Imperative. 1.03 against 0.3.
import java.util.*;
public class Main
{
public static void main(String[] args)
{
List<Integer> numbers = new ArrayList();
int size = 200000000;
//add objects to collection
for(int i = 0; i <= size; i++)
{
numbers.add(i);
}
//functional
long timer = System.nanoTime();
if(numbers.contains(size))
{
System.out.println(System.nanoTime() - timer) / 1000000000.0);
}
//imperative
timer = System.nanoTime();
for(Integer num : numbers)
{
if(num.equals(size))
{
System.out.println(System.nanoTime() - timer) / 1000000000.0);
break;
}
}
}
}
So, question is:
- Why functional search complete faster?
Appreciate your response