Paul
Paul

Reputation: 9445

profiling anonymous javascript functions (chrome)

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 determine where an anonymous function was first instantiated?

Upvotes: 11

Views: 3848

Answers (3)

guest271314
guest271314

Reputation: 1

You can utilize console.profile([label]), console.profileEnd(), console.time([label]), console.timeEnd([label]).

For example, execute the below in the JS snippet in console then review the anonynous function execution profile under 'Customize and control DevTools > More tools > JavaScript Profile'.

console.profile("anonymous function");
console.time("anonymous function");
(function() {
  var a = 123;
  function abc() {
    return a
  }
  abc();
}());
console.timeEnd("anonymous function");
console.profileEnd();

enter image description here

TIP: Storing JS in DevTools Snipets: Select Sources -> Snippets -> right-click -> select New -> place javascript within middle panel -> highlight / select text of javascript within middle panel -> right-click -> select Evaluate in Console -> click right-triangle at right panel or Ctrl+Enter.

Upvotes: 10

Apolo
Apolo

Reputation: 4050

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 !

Upvotes: 4

Yordan Ivanov
Yordan Ivanov

Reputation: 580

Probably the easiest way is to put a console.trace() in your function.

Upvotes: 2

Related Questions