HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

hand optimising javascript selector function

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
selectorhandjavascriptfunctionoptimising

Problem

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 ` QSA is slow as hell and should be avoided `

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?

Solution

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
}

Code Snippets

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
}

Context

StackExchange Code Review Q#6687, answer score: 3

Revisions (0)

No revisions yet.