profiling anonymous javascript functions (chrome)

后端 未结 3 1136
星月不相逢
星月不相逢 2021-01-17 21:57

when performance profiling in chrome anonymous high-use functions are difficult to trouble-shoot when they are listed at the root of the call tree. is there a way to determ

3条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-17 22:24

    To find the origin of every call

    1 - as Yordan said, you can use console.trace.

    2 - You can also try :

    console.log("called from : " + arguments.callee.caller.name.toString());
    

    BUT this may be impossible in strict mode

    window.addEventListener("load", function() {
      var anon = function() {
        console.log("called from : " + arguments.callee.caller.name.toString());
      };
      
      function Test() {
        anon();
      }
      var anon2 = function() {
        anon();
      }
      
      Test(); // will display "Test"
      anon2(); // won't display a name (Anonymous caller)
    });

    If you need to profile a code block (in anonymous function or not) you can use console.profile / console.profileEnd and console.time / console.timeEnd (see guest271314 answer)

    I recently made a little javascript plugin to help me debug time consumption in my apps : MonitorJS (1.35KB)

    You can use it to measure how many CPU time a code block (function or not) is using over time.

    e.g. :

    // ...
    
    function Test() {
      var mId = Monitor.Start("Foo");
    
      // Test function code
      // ...
    
      Monitor.Stop(mId);
    }
    

    Then you can check anytime in console :

    Monitor.Get("Foo");
    // return an object :
    {
       name: "Foo",
       call_count: 32,
       // time in milliseconds, accurate to one thousandth of a millisecond
       total_time: 654.685
    }
    // you can calculate the average time per call
    

    See the docs on Github

    Hope this helps !

提交回复
热议问题