If I define a function
inc = function(x) { return x + 1 }
and make his nested appeal
inc(inc(inc(inc(inc(inc(inc(inc(inc(inc(inc(inc(inc(inc(inc(inc(inc(inc(inc(inc(inc(1)))))))))))))))))))))
this will result in a value of 22 . If I revise the nested expression, use call instead, going null for this , like
inc.call(null, inc.call(null, inc.call(null, inc.call(null, inc.call(null, inc.call(null, inc.call(null, inc.call(null, inc.call(null, inc.call(null, inc.call(null, inc.call(null, inc.call(null, inc.call(null, inc.call(null, inc.call(null, inc.call(null, inc.call(null, inc.call(null, inc.call(null, inc.call(null, 1)))))))))))))))))))))
this will also result in a value of 22 .
But on JavaScriptCore, this second form consumes O (2 ^ n) memory, where n is the number of nested calls. This is not the case if I try to use this JavaScript in Firefox or Chrome, so it seems to be isolated from JavaScriptCore.
I have very little experience with JavaScript (almost none). I do not feel the trade-offs that may arise in various JavaScript implementations, and is it not reasonable for the example code to be expensive in some implementations (providing general support for closing or some of them), although it is effective in others.
My question is: Is this code inherently problematic? Should it be rewritten differently? Or the code is fine: does JavaScriptCore just have a bug?
I conducted several experiments in which refactoring several internal calls in time will βtruncateβ memory doubling behavior
var temp1 = inc.call(null, inc.call(null, inc.call(null, inc.call(null, inc.call(null, inc.call(null, inc.call(null, 1))))))); var temp2 = inc.call(null, inc.call(null, inc.call(null, inc.call(null, inc.call(null, inc.call(null, inc.call(null, temp1))))))); inc.call(null, inc.call(null, inc.call(null, inc.call(null, inc.call(null, inc.call(null, inc.call(null, temp2)))))));