This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
I was trying out different ways of iterating over huge collections and wanted to understand the results. This is not done for any specific use case or practical requirement.
I think i have come across case-2 in "effective java" book.
When I ran this multiple times, the results varied.
Iter loop time = 1766
Iter loop time = 1422
Iter loop time = 1484
Iter loop time = 1656
Iter loop time = 1531
Iter loop time = 1453
Iter loop time = 1594
Iter loop time = 1453
Iter loop time = 1312
Iter loop time = 1672
Iter loop time = 1516
Iter loop time = 1562
My questions are :
1. Why is the time taken differing for the same loop in multiple runs? loop1 took 1766, 1656, 1594 etc. what all does it depend on?
2. Why is loop3 taking longer time(surprisingly only sometimes) compared to loop2? Shouldn't case3 be the one executing the fastest of all the above 3?
Appreciate any thoughts or comments on this behaviour.
Completely missed the part that loop3 is the only one iterating through the list. Thanks for pointing to that.
Ok, in that case, i cannot compare it with loop 1 and 2.
Without the print statements inside the loops, I could not even measure the time taken for each loop. The diff1 or diff2 was printing as 0.
Between loop1 and loop2, i.e,
for(int i=0; i<list.size();i++)
for(int i=0, j=list.size(); i<j;i++)
will there be any difference? does getting the list.size() into j in loop2 rather than getting it for each iteration in i<list.size in loop 1 save any time?
Agreed that it is very trivial. But wanted to know if it saves at least any micro or nano seconds? or it does not make any difference at all?
Your testing method is a bit naive. You should most likely profile each iteration method in isolation for at least few minutes
to reach any conclusions. Actually I did something similar when testing mahout claims they had "fast" collections.
My findings were that the good old simple for was the fastest of the lot. I don't have the results handy but I'll try to find them.