Tell me, can anyone come across. From the point of view of optimization, if a constructor needs an auxiliary function to create an object, is it better to save it in a closure or make it a constructor method?

function Foo() { function func() {} } 

or

 function Foo() { } Foo.func = function() {} 

or doesn't matter? besides the fact that in the second case the method will be public

  • What does this feature do? - Grundy
  • @Grundy let's say the data is formatted before assigning a property to a property - Kot

1 answer 1

Such things just need to take and measure. In theory, the nested function should be slower, since it is created every time you call an external one.

In any case, it is highly unlikely that this will cause the script to work slowly.

 function test(f) { var t = performance.now(); for (var q=0; q<1000000; ++q) { var x = new f(); } t = performance.now() - t; console.log((""+f).match(/function\s+(\w+)/)[1] + " " + t.toFixed(3) + " ms"); } function local() { function other(a) { ax = 90; } other(this); } var closure = (function () { function other(a) { ax = 90; } return function closure() { other(this); } })(); function field() { field.other(this); } field.other = function other(a) { ax = 90; }; test(local); test(closure); test(field); 

PS: I have in Chrome a difference of 5-10 times against the nested function. But in fact, this is not the difference at times, but for a certain number of operations, so a comparison on empty or almost empty functions makes little sense.

  • in firefox, the local function wins, with some cosmic advantage. probably the cycle is fully optimized - Grundy
  • @Grundy, Yandex browser - the local function loses 2 times. - Qwertiy
  • still in IE / EDGE you should try :-) local: 84, closure: 44, field: 60 - Grundy
  • @Grundy, just poporbovat. The difference between the ways is minimal in Edge - everything is from 30 to 50. - Qwertiy
  • Do you have a safari to try? - Grundy