Better use of Memoization JavaScript

Referring to the post Generating Unique Strings (Ids) in JavaScript where we looked at how to generate unique strings in JavaScript. Also I mentioned the performance and memory issues with the approach.

So, here we are going to look a much better use or application of Memoization, but we won’t be using it for generating unique strings. We will be looking at another issue and will try to find an efficient way to handle it.

We all know that accessing DOM elements is pretty much costly in terms of performance. Lets look at an example of such an issue.

    function someFunction() {
        var text = document.getElementById("some-id").innerHTML;
        return text;
    }

Now suppose the above function is executed several times(reason could be anything like, user clicks). Every time this function is executed, it traverses the DOM and then returns it, which makes it really inefficient.
Now, I hope we have the idea of how to solve problem. Exactly, we will simply access the element one time and store it in a cache rather than looking into the DOM again and again.
So, here is how to do it:

    function someFunction() {
        if(someFunction.cachedElement) {
            return someFunction.cachedElement.innerHTML;
        } else {
            var ele = document.getElementById("some-id");
            someFunction.cachedElement = ele;
            return ele.innerHTML;
        }
    }

This technique can be more efficient if we are looking for multiple elements for example by className of the elements. In that case, we just need to get all the elements only once and store them in an array. So next time when the function is called all the elements are returned from the cache rather than going through whole DOM.
Pretty fast haan, isn’t it!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s