Calling to functions that return the same value over and over to test the exit condition on a loop is a very novel error or mistake, but I have seen it multiple times in different programming languages. At the end, the problem is the programmer relying on the compiler optimization, which I think is a bad practice. Write efficient code and let the compiler do its job. But don’t rely on it to optimize your inefficient code. Not to say than there is no compiler optimization at all when writing interpreted code like Python or Javascript.
Here is a simple test to show how adding a simple string.length call on a loop impacts the performance.
-
var text = "Calling to functions that return the same value over and over to test the exit condition on a loop is a very novel error or mistake, but I have seen it multiple times in different programming languages. At the end, the problem is the programmer relying on the compiler optimization, which I think is a bad practice. Write efficient code and let the compiler do its job. But don't rely on it to optimize your inefficient code. Not to say than there is no compiler optimization at all when writing interpreted code like Python or Javascript.";
-
var iterations = 100000;
-
-
var start_slow = (new Date()).getTime();
-
for (var n=0; n<iterations; n++) {
-
for (var i=0; i<text.length; i++) { // Call to text.length inside loop is executed N times
-
// Nothing to do
-
}
-
}
-
var end_slow = (new Date()).getTime();
-
-
var start_fast = (new Date()).getTime();
-
var l = text.length; // Call to text.length outside the loop is executed only once
-
for (var n=0; n<iterations; n++) {
-
for (var i=0; i<l; i++) {
-
// Nothing to do
-
}
-
}
-
var end_fast = (new Date()).getTime();
-
-
console.log('Slow:' + (end_slow – start_slow));
-
console.log('Fast:' + (end_fast – start_fast));
Note: I have tested it on Firefox 3.0 and Safari 3.2. The second seems to have a bigger performance impact.
Firefox: Slow: 3,667ms Fast: 3,342ms
Safari: Slow: 6,273ms Fast: 2,157ms
Demo: http://code.enekoalonso.com/js/tests/strlen-loop-test.html
Well, in fact oriented object languages use to have good implementations for “length” and similar functions (using a variable where length is stored, so once is computed, access is O(1)), no matter if they are interpreted or compiled.
I’m impressed about your example on Safari, I though the implementation of string length would be good.
About ‘don’t rely on compilers to optimize your programming faults’, check this other article:
Un error comun en programacion: lenguages compilados
The conclusion for G++ is: the compiler is able to optimize strlen, but not other functions that could be optimized as well.
So as you said, is not a good idea to rely or interpreters or compilers.
Yes, I saw that one too. I agree. Do not rely on compilers. Do your best and they’ll do their best :)