Thursday 15 January 2015

performance - Javascript heavily executed functions: inline or declared? -


It is safe to assume that it is better to use the function declaration or function expression instead of the inline function for time-critical applications Is In Heavily Executed Callback?

Consider the following test program:

  var x; Var count3 = function count3 () {x ++; } Var count2 = function () {x ++; } Function count () {x ++; } Function Execution (CB) {cb (); } X = 0; Var a = New Date () GetTime (); (Var i = 0; i & lt; 100000000; i ++) {execute (function name () {x ++;})} a = New date (). GetTime () - a; Console.log ("Named Inline Function:" + a); X = 0; A = new date () GetTime (); (Var i = 0; i & lt; 100000000; i ++) {execute (function () {x ++;})} a = New date () GetTime () - a; Console.log ("Anonymous Inline Function:" + a); X = 0; A = new date () GetTime (); (Var i = 0; i & lt; 100000000; i ++) {execute (calculation); A = new date (). GetTime () - A; Console.log ("Function declaration:" + a); X = 0; A = new date () GetTime (); (Var i = 0; i & lt; 100000000; i ++) {execute (count2); A = new date (). GetTime () - A; Console.log ("Anonymous Function Expression:" + a); X = 0; A = new date () GetTime (); (Var i = 0; i & lt; 100000000; i ++) {execute (count3); A = new date (). GetTime () - A; Console.log ("Named Function Expression:" + a);   

This gives the following output (in MS):

  Named Inline Function: 2347 Anonymous Inline Function: 2121 Function Declaration: 771 Anonymous Function: 750 Nominated Function Expression: 752   

Function announcement and function expressions are 3 times faster than inline function on my meek laptop.

Yes, it can be normalized technically in the loop body, the function expression on each function object Each loop is re-evaluated for the twist. According to your tests confirmation, it is noticeably slower (for millions of iterations) than a "static" function defined outside of the loop, whether or not the function has been given the name, does not really make any difference, its execution references There is very little overhead in presenting another variable.

However, this is only relevant when the function is actually declared in the running, in your examples if you have a

  function execution all instead (CB) { (Var i = 0; i & lt; 100000000; i ++) was for {cb (); }}   

then

  there is no difference between executeAll (function () {x ++;});   

and

  function increase () {x ++; } All executed (growth);   

Because cb argument is a "stable" reference of a function.

No comments:

Post a Comment