seyDoggy
seyDoggy

Reputation: 140

If an if block returns in JavaScript, is there a need for else?

I'm currently trying to squeeze every last millisecond from a JavaScript program that is fired on an event listener at a rate of 10x per second. I'm trying to remove all cruft. When an if block's sole purpose is to return something if true, is there any advantage to following with else if or else, or am I right in thinking that I forgo else.

eg.

// with else
function withElse () {
    if (foo) {
        return foo;
    } else if (bar) {
        return bar;
    } else {
        return baz;
    }
}

// without else
function withoutElse () {
    if (foo) return foo;
    if (bar) return bar;
    return baz;
}

Upvotes: 0

Views: 94

Answers (2)

t.pimentel
t.pimentel

Reputation: 1575

Answering your question, there's no difference between the two programs and you can leave it out if you want.

But, as @torazaburo said "The else is going to cost a microsecond or two at compile time". But, for what I know, it doesn't make any difference at run time, so even if you're calling this function 1000x per second you aren't optimizing anything.

if (foo) {
    return foo;
} else if (bar) {
    return bar;
} else {
    return baz;
}

Will be compiled (by a stupid compiler) to something like this (but in assembly):

1. ifnot (foo) goto line 4;
2. return foo;
3. goto line 9;
4. ifnot (foo) goto line 7;
5. return foo;
6. goto line 9;
7. ifnot (foo) goto line 9;
8. return foo;
9. 

Against:

if (foo) return foo;
if (bar) return bar;
return baz;

That would be:

1. ifnot (foo) goto line 3;
2. return foo;
3. ifnot (foo) goto line 5;
4. return foo;
5. ifnot (foo) goto line 7;
6. return foo;
7. 

The performance is the same! (I also prefer the second for readability!)

Ps: If you think I'm saying anything wrong, please correct me

Upvotes: 0

T.J. Crowder
T.J. Crowder

Reputation: 1074138

No, there isn't. You may choose to have it for clarity, but it's not required (and you may choose not to have it to avoid redundancy; it's totally a style choice).

(Similarly, you may choose to always have the block — {...} — for clarity, but it's not required either.)

Neither of those things matters from a performance standpoint.

There's a third choice to consider:

function withElse () {
    var rv;

    if (foo) {
        rv = foo;
    } else if (bar) {
        rv = bar;
    } else {
        rv = baz;
    }

    return rv;
}

More verbose, but it has the advantage that the function exits in a single location, which can be useful for debugging. It has the disadvantage, of course, of...being more verbose. :-)

On a simplistic engine, that third choice may have a tiny, tiny performance penalty; on an optimizing engine such as found in modern browsers, I very much doubt it does.

Upvotes: 4

Related Questions