#33 ✓invalid
Offshore

Speed enchancement for $()

Reported by Offshore | April 20th, 2008 @ 09:14 PM

The getElementById() function is senibly slow, so the often calls of $ function can affect the performance of whole script.

The "problem" can be solved by using cache array for oftenly used elements (global scope):

var g_elementCache = new Array();

And writing the following code (function $()):

element = (typeof g_elementCache.element == 'undefined') ? (g_elementCache[element] = document.getElementById(element)) : g_elementCache[element];

Instead of existing

element = document.getElementById(element);

thanx for your attention :)

Comments and changes to this ticket

  • Juriy Zaytsev

    Juriy Zaytsev April 21st, 2008 @ 12:07 AM

    I'm afraid that due to a highly dynamic nature of web applications, storing elements in a cache is quite of a memory hog. Barely noticeable speed improvements are not worth it.

  • Andrew Dupont

    Andrew Dupont April 21st, 2008 @ 12:07 AM

    • State changed from “new” to “invalid”

    This optimization assumes that $('foo') will return the same thing at every single point in the page's life cycle. But I could remove that element, create another element with the same ID, and add it to the DOM. For that reason, we can't cache calls to document.getElementById.

  • Offshore

    Offshore April 21st, 2008 @ 11:52 AM

    Juriy Zaytsev, it's creating just a reference, not an indexed clone of an element.

    Andrew Dupont, just in this case, you are right.

Please Sign in or create a free account to add a new ticket.

With your very own profile, you can contribute to projects, track your activity, watch tickets, receive and update tickets through your email and much more.

New-ticket Create new ticket

Create your profile

Help contribute to this project by taking a few moments to create your personal profile. Create your profile ยป

The Prototype JavaScript library.

Shared Ticket Bins

Pages