This is not a duplicate of my question. I checked it and it is more about inner anonymous classes.
I was curious about Lambda expressions and tested the following :
- Given an array of ten thousand entries, what would be the faster to delete certain indexes : Lamba expression or For-Loop with an if test inside?
First results were not surprising in the fact that I did not know what I was going to come up with :
final int NUMBER_OF_LIST_INDEXES = 10_000;
List<String> myList = new ArrayList<>();
String[] myWords = "Testing Lamba expressions with this String array".split(" ");
    
for (int i = 0 ; i < NUMBER_OF_LIST_INDEXES ; i++){
    myList.add(myWords[i%6]);
}
        
long time = System.currentTimeMillis();
        
// BOTH TESTS WERE RUN SEPARATELY OF COURSE
// PUT THE UNUSED ONE IN COMMENTS WHEN THE OTHER WAS WORKING
        
// 250 milliseconds for the Lambda Expression
myList.removeIf(x -> x.contains("s"));
        
// 16 milliseconds for the traditional Loop
for (int i = NUMBER_OF_LIST_INDEXES - 1 ; i >= 0 ; i--){
    if (myList.get(i).contains("s")) myList.remove(i);
}
System.out.println(System.currentTimeMillis() - time + " milliseconds");
But then, I decided to change the constant NUMBER_OF_LIST_INDEXES to one million and here is the result :
final int NUMBER_OF_LIST_INDEXES = 1_000_000;
List<String> myList = new ArrayList<>();
String[] myWords = "Testing Lamba expressions with this String array".split(" ");
    
for (int i = 0 ; i < NUMBER_OF_LIST_INDEXES ; i++){
    myList.add(myWords[i%6]);
}
    
long time = System.currentTimeMillis();
    
// BOTH TESTS WERE RUN SEPARATELY OF COURSE
// PUT THE UNUSED ONE IN COMMENTS WHEN THE OTHER WAS WORKING
    
// 390 milliseconds for the Lambda Expression
myList.removeIf(x -> x.contains("s"));
    
// 32854 milliseconds for the traditional Loop
for (int i = NUMBER_OF_LIST_INDEXES - 1 ; i >= 0 ; i--){ 
    if (myList.get(i).contains("s")) myList.remove(i);
}
System.out.println(System.currentTimeMillis() - time + " milliseconds");
To make things simpler to read, here are the results :
|        |  10.000 | 1.000.000 |
| LAMBDA |  250ms  |   390ms   | 156% evolution
|FORLOOP |   16ms  |  32854ms  | 205000+% evolution
I have the following questions :
- What is magic behind this? How do we come to such a big difference for the array and not for the lambda when the indexes to work with is *100. 
- In terms of performance, how do we know when to use Lambdas and when to stick to traditional ways to work with data? 
- Is this a specific behavior of the - Listmethod? Are other Lambda expression also produce random performances like this one?
 
     
     
     
    