javascript - Conditional evaluation of callback arguments -
recently i've been getting javascript ecosystem. after sometime javascript's callbacks started asking myself if javascript interpreters capable of doing conditional evaluation of callback arguments. let's take following 2 example:
var = 1; var b = 2; // example 1 abc.func(a, b, function (res) { // res }); // example 2 abc.func(a, b, function () { // });
from understand, javascript uses arguments
object keep track of passed function. regardless of function definition is. assuming that:
abc.func = function (a, b, cb) { // stuff var res = {}; // expensive computation populate res cb(res); }
in both examples (1, 2) res
object passed arguments[0]
. in example 1 res === arguments[0]
since res
parameter defined.
let's assume computing res
expensive. in example 1 it's ok go through computation since res
object used. in example 2, since res
object not used, there no point in doing computation. although, since arguments
object needs populated, in both cases computation populate res
done. correct ?
assuming that's true, seems (potentially) huge waste. why compute that's going go out of scope , garbage collected ? think of libraries out there use callbacks. lot of them send multiple arguments callback function, none of them used.
is there way prevent behaviour. make javascript interpreter smart enough not compute specific variables turn unused arguments ? in example 2 res
object not computed since never used.
i understand until point things used:
function xyz(a, b /*, rest */) // use arguments iterate on rest }
so default makes sense still compute arguments. let's forward ecmascript 2015. include ...rest
parameter defined. engines support new version, there way enable conditional evaluation? make more sense, since there way explicitly ask evaluate , pass in arguments function.
no, javascript not lazy call-by-name language. because expressions can have side effects, , es standard requires them executed in order programmer expects them.
yes, js engines smart. if detect code not execute side effects, , results not used anywhere, dumps them (dead code elimination). i'm not sure whether works across function boundaries, guess doesn't, if in hot code path , call inlined, might optimised.
so if know doing heavy computation, may want make lazy explicitly passing thunk. in eagerly evaluated language, typically represented function takes no parameters. in case:
abc.func = function (a, b, cb) { // stuff var res = {}; cb(() => { // expensive computation populate res return res; }); } // example 1 abc.func(a, b, function(getres) { var res = getres(); // res }); // example 2 abc.func(a, b, function() { // no heavy computation // });
Comments
Post a Comment