views:

54

answers:

2

Hi guys,

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.

+3  A: 

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);
Amarghosh
A string is not by all means an instance of `String` (not `string`!). `typeof` is the right way to go.
Gumbo
@Gumbo changed.
Amarghosh
+1  A: 

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: http://stackoverflow.com/questions/855126/what-is-the-best-way-to-profile-javascript-execution

Good luck!

Gdeglin