Just a learner
Just a learner

Reputation: 28572

Does this javascript statement affects performance?

I'm writing a function add_event as the following shows:

function add_event(o, event_type, callback, capture){
    o = typeof o === "string" ? document.getElementById(o) : o;
    if(document.addEventListener){
        add_event = function(o, event_type, callback, capture){
            o = typeof o === "string" ? document.getElementById(o) : o;
            o.addEventListener(event_type, callback, capture);
        }
    }else if(document.attachEvent){
        add_event = function(o, event_type, callback, capture){
            o = typeof o === "string" ? document.getElementById(o) : o;
            o.attachEvent("on" + event_type, callback);
        }
    }
    add_event(o, event_type, callback, capture);
}

Now my question is whether the statement

o = typeof o === "string" ? document.getElementById(o) : o;

affects the performance of this program? If you pass an HTML element instead of an id, you infact executes the statement o = o, this is the reason why I ask this question. Great Thanks.

Upvotes: 1

Views: 134

Answers (2)

Amarghosh
Amarghosh

Reputation: 59451

Chances are that the js interpreter will optimize it out. Even if it doesn't, the effect won't be noticeable. And if you're really concerned, change it to:

if(typeof o === "string")
  o = document.getElementById(o);

Upvotes: 3

Gdeglin
Gdeglin

Reputation: 12618

No. Most javascript interpreters will not have their performance affected by this. Those that do will have it affected by a few microseconds at most.

In cases like this you should focus on making your code readable and maintainable. Trying to squeeze performance out of very simple operations is only going to waste time and possibly make your code harder to maintain.

If you feel that your javascript code is performing poorly, there are a variety of tools and strategies you can use to find and fix the problem. The following stack overflow question has more on the topic: What is the best way to profile javascript execution?

Good luck!

Upvotes: 2

Related Questions