Christian Harris
Christian Harris

Reputation: 99

Detect slow Javascript

Is there any way to detect if Javascript code is taking more time to execute than it should? I don't want to run code, then determine the time it took, I want to determine if actively running code is going slower than it should, and stop that whole script.

Upvotes: 1

Views: 4853

Answers (3)

Stanley Stuart
Stanley Stuart

Reputation: 1145

I really liked Nicholas Zakas's presentation titled Speed Up Your JavaScript. Some points to mention from it:

  • Try avoiding accessing the DOM too much. If you're accessing a variable in the DOM (such as document.getElementById('blah), store it in a local variable.
  • Avoid using the global namespace, and use closures only when you need them. Learn how the stack works in JavaScript and you'll see how this makes sense.
  • Counting down in for loops tends to be faster
  • Avoid while, and the catch part of try/catch. For/for in seem to have some performance issues as well.
  • Be wary of HTMLCollection objects.

This information is a couple years old, but there are a lot of good practices in the presentation.

Upvotes: 3

Wasim Karani
Wasim Karani

Reputation: 8886

The YSlow add-on is the best solution to know why your website is slow.

enter image description here

There are many issues which could be the reason for slowness.

Combining many jQuery to one could help you increasing your performance.

Also you can put the script at the bottom of your page and CSS at top.

Upvotes: 2

tskuzzy
tskuzzy

Reputation: 36446

There's no concrete measure of how long a script "should" run. If you want to find where your code is slowest though, I would use a profiler.

FireBug has one and so do most other developer tools.

Upvotes: 2

Related Questions