Tim Tim - 25 days ago 15
Javascript Question

JavaScript DOM performance

I have a lot of elements in my code which will have to be hidden and displayed dynamically. Hence I will be using a number of

document.getElementById('x').style.display
. I have decided to use different method by creating two functions to do the job for me like this:

function displayNone(a){document.getElementById(a).style.display= "none";}
function displaybloack(a){document.getElementById(a).style.display="block";}


then I will be just calling these functions with the relevant ID as an argument.

My question: is there any performance hit when using one method over simply using
document.getElementById('x').style.display
directly not through a function call?

Answer

My question: is there any performance hit when using one method over the other?

Yes. The function call will be slower.

The question is how much. The answer is some incredibly small amount. It is even possible that some engines might in-line the call, making the performance penalty nil. Even if they don't, the performance hit is probably measured in sub-microseconds.

As with any other potential performance concern, the correct approach is to build your app, then find the performance bottlenecks, then fix them.

On a separate topic, as a commenter mentioned, don't refer to DOM elements by their IDs, Instead, refer to them as themselves. Don't pass an ID to a function as you are doing, and find the element from the ID each time the function is called. Instead, pass the DOM element to your function. The cost of doing getElementById over and over ago will swamp any cost from an extra function call.

You should also prefer not to set styles directly. Instead, define a class such as

.hide { display: none; }

and turn your elements on and off by adding or removing that class from the element:

function hide(e) { e.classList.add('hide'); }
function show(e) { e.classList.remove('hide'); }
Comments