Performance of function declaration vs function expressions in javascript in a loop -
in next jsperf: http://jsperf.com/defined-function-vs-in-loop-function/3
you notice code:
for (var = 0; < loops; i++) { function func(a, b) { homecoming + b; }; func(i, i); } performs on par code:
function declaredfn(a, b) { homecoming + b; }; (i = 0; < loops; i++) { declaredfni, i); } but code:
for (i = 0; < loops; i++) { var func = function(a, b) { homecoming + b; }; func(i, i); } is slower code:
var expfunc = function(a, b) { homecoming + b; }; (i = 0; < loops; i++) { expfunc(i, i); } why? happening internally?
if define function using function fn() {} declaration, gets hoisted top. therefore, code:
for (var = 0; < loops; i++) { function func(a, b) { homecoming + b; }; func(i, i); } is exactly equivalent code:
function declaredfn(a, b) { homecoming + b; }; (i = 0; < loops; i++) { declaredfn(i, i); } because function declaration gets hoisted top.
however, var fn = function() {} expressions do not hoisted, end defining function on over every single loop.
see this answer more info.
javascript performance
No comments:
Post a Comment