Monday, January 6, 2014

Performance of a shortcut to document.getElementById

I don't like typing document.getElementById (or document.createElement, etc.) repeatedly so for a while now, I've used my own function, I call byId (I know jQuery has $get, but I don't use jQuery, for reasons I won't go into here). This function started out as a simple:

function byId(id)
{
 return document.getElementById(id);
}

In Internet Explorer, I could use var byId = document.getElementById, but this didn't work in other browsers. I then tried, what I though was a more elegant solution of binding byId to the document object (var byId = document.getElementById.bind(document)). This works, but it winds up being slower then then simple method in all browsers, but IE. I decided to publish my results on jsperf for anyone interested.

What's really maddening is that the best method is different in each browser. I'm sure any web developers have experienced this themselves.

No comments:

Post a Comment