Which piece of code is faster
Number 1:
for(var i = 0; i<50; i++){
//run code in here
}
for(var i = 0; i<50; i++){
//run more code in here
}
Or number 2:
for(var i = 0; i<100; i++){
//run all the code in here
}
Thanks!
Which piece of code is faster
Number 1:
for(var i = 0; i<50; i++){
//run code in here
}
for(var i = 0; i<50; i++){
//run more code in here
}
Or number 2:
for(var i = 0; i<100; i++){
//run all the code in here
}
Thanks!
As already pointed out in another answer, both loops yield the same O(N) scaling behaviour (for whatever happens in the loop body as well as for scaling the loop lengths 50 and 100, resp. The point usually is the proportional factor that accompanies the power term (c . XN).
On many (most) real CPU systems used for performance-relevant computation, there are usually caches and pipelines for the data manipulated inside the loops. Then, the answer to the question depends on the details of your loop bodies (will all the data read/written in the loops fit into some level of cache, or will the second 50-loop miss all existing cache values, and retrieve data from memory again?). Additionally, speculation of branch prediction (to the loop exit/repeat branch as well as to those inside the loop) has a complicated influence on the actual performance.
It is an own section of computational science to take into account all relevant details exactly. One should analyse the concrete example (what do the loops do actually?) - and before, whether this loop is actually relevant.
Some heuristic may nevertheless be helpful:
If i is an iterator (and not only a repetition counter), the two 1..50 loops might be working on the same data.
If it is possible to treat every element by both loop bodies (which only works if there are no dependencies between the second loop and the state of other elements after the first loop), it is usually more efficient to treat each index only once.
It would depend on the logic inside of them (nested loops etc). Theoretically, They'd run the same, as they're both linear. (Both are 100 iterations). So the Big O Time Complexity is O(N), where N is the size of the loop.