hand optimising javascript selector function I personally want a small selector function that covers the three common cases


getElementById
getElementsByClassName
getElementsByTagName


It should support contexts and should not support querySelectorAll since &lt;opinionated&gt; QSA is slow as hell and should be avoided &lt;/opinionated&gt;

I have an implementation of such a function

function select(selector, context) {
    var c = selector.charAt(0),
        method;

    if (c === "#") {
        method = "getElementById";
        selector = selector.substring(1);
    } else if (c === ".") {
        method = "getElementsByClassName";
        selector = selector.substring(1);
    } else {
        method = "getElementsByTagName";
    }

    return (context || document)[method](selector);
}


And I have a benchmark.

As can be seen it's still a factor of 4 away from native support.

Can I hand optimise this further? And if so, how?
This is twice as slow as native (the original being 4x as slow)

function select (selector, context) {
    var c = selector.charAt(0), 
        method,
        context = context || document;

    if (c === '#') {
        selector = selector.substring(1);
        method = context.getElementById(selector);
    } 

    else if (c === '.') {
        selector = selector.substring(1);
        method = context.getElementsByClassName(selector);
    } 

    else {
        method = context.getElementsByTagName(selector);
    }

    return method
}