views:

201

answers:

4

I was fine tuning a page that is heavy on jquery and stumbled across this website:

http://www.componenthouse.com/extra/jquery-analysis.html

When I click on the "Run Test" button the first time, the numbers are way higher than subsequent clicks. Is this because JS is cached by the browser? Can someone explain how this works internally? Can a user choose to not cache the JS?

+1  A: 

External javascript files are cached and off course, an html containing script tags can be cached too. What you see may be a result of html caching or some browser optimization. You should try different browsers, closing and re-opening your browser and clearing the cache of the browser.

Procrastinator2
If you hit reload, you get slower times again, so it's not due to files being cached.
Alan
What he's seeing is jQuery caching the selector query results.
Eli Grey
Elijah, I'm not sure that's true. Run it in the Firebug profiler and compare the results; the jQuery execution code times are similar on 1st and 2nd runs.
Craig Stuntz
+1  A: 

Whether or not JavaScript code is cached, execution performance isn't affected. What you are seeing is jQuery caching the results for the selector queries so they don't take as long on subsequent runs.

Eli Grey
If that were the principal cause of the difference I'd expect to see similar behavior in IE 8.
Craig Stuntz
There's no performance gain in subsequent runs. Tested in 5 different browsers (and 2 different versions of IE), the number was stable from the first and all subsequent runs. The guy was probably loading much CPU during the first test and thought it had something to do with cacheing.
Havenard
Havenard, you and I are seeing different results, then. I see consistently faster execution on the second and all subsequent runs on Firefox 3.5.
Craig Stuntz
I'm seeing the same behavior (consistently faster on second and subsequent runs) in Google Chrome, too (though less dramatically faster; Chrome is faster to begin with).
Craig Stuntz
A: 

The numbers are (significantly) different for me on the second time in Firefox 3.5. OTOH, they are fairly consistent(ly slow) in IE 8. Firefox 3.5's JavaScript interpreter compiles the JS to executable code. So it does make sense that the first time is slower; the code hasn't been JITted yet.

Craig Stuntz
+1  A: 

The performance boost you're seeing is likely due to your javascript interpreter. Most newer web browsers use a JIT-compiling javascript engine so code paths taken multiple times can be optimized.

Read this blog post on how Safari's javascript engine achieved many of its speed-ups.

Duncan Beevers