In javascript, what are the trade-offs for defining a function inline versus passing it as a reference? -
so, let's have large set of elements want attach event listeners. e.g. table want each row turn red when clicked.
so question of these fastest, , uses least memory. understand it's (usually) tradeoff, know best options each.
using table example, let's there's list of row elements, "rowlist":
option 1:
for(var r in rowlist){ rowlist[r].onclick = function(){ this.style.backgroundcolor = "red" }; }
my gut feeling fastest, since there 1 less pointer call, memory intensive, since each rowlist have own copy of function, might serious if onclick function large.
option 2:
function turnred(){ this.style.backgroundcolor = "red"; } for(var r in rowlist){ rowlist[r].onclick = turnred; }
i'm guessing going teensy bit slower 1 above (oh no, 1 more pointer dereference!) lot less memory intensive, since browser needs keep track of 1 copy of function.
option 3:
var turnred = function(){ this.style.backgroundcolor = "red"; } for(var r in rowlist){ rowlist[r].onclick = turnred; }
i assume same option 2, wanted throw out there. wondering difference between , option 2 is: javascript differences defining function
bonus section: jquery
same question with:
$('tr').click(function(){this.style.backgroundcolor = "red"});
versus:
function turnred(){this.style.backgroundcolor = "red"}; $('tr').click(turnred);
and:
var turnred = function(){this.style.backgroundcolor = "red"}; $('tr').click(turnred);
here's answer:
http://jsperf.com/function-assignment
option 2 way faster , uses less memory. reason option 1 creates new function object every iteration of loop.
Comments
Post a Comment