obj = [1,2,3,4,5];
function iter(){
for (var key in obj){
key=key+key;
};
};
function test1() {
iter(obj);
};
function test2(){
(function iter(obj){
for (var key in obj){
key=key+key;
};
})(obj);
};
Here, both test1 and test2 perform the same, even though test2 is supposedly creating a new function everytime it is called. Why?
My guess is that there’s no difference in performance because there’s no (meaningful) difference in the code. The parser creates the localWell, that was wrong.iterfunction insidetest2once when it parses the code, not each timetest2is called. (This isn’t like usingeval.) If anything, the second one will be a tiny bit faster becauseobjis local to theiterfunction.As this jsperf test shows, the second is indeed slower. You have to be careful about measurement. The way you wrote the functions, the amount of work being done in the function bodies easily masks the difference in function call overhead involved in the two cases. Also, the first case is accessing a global
obj, while the second is accessing an argument. These differences should be eliminated to, as much as possible, measure only what you’re trying to measure. The jsperf test I wrote tries to do just that.