Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
514 views
in Technique[技术] by (71.8m points)

performance - Javascript && operator versus nested if statements: what is faster?

Now, before you all jump on me and say "you're over concerned about performance," let it hereby stand that I ask this more out of curiosity than rather an overzealous nature. That said...

I am curious if there is a performance difference between use of the && ("and") operator and nested if statements. Also, is there an actual processing difference? I.e., does && always process both statements, or will it stop @ the first one if the first one fails? How would that be different than nested if statements?

Examples to be clear:

A) && ("and") operator

if(a == b && c == d) { ...perform some code fashizzle... }

versus B) nested if statements

if(a == b) {
    if(c == d) { ...perform some code fashizzle... }
}
question from:https://stackoverflow.com/questions/3126201/javascript-operator-versus-nested-if-statements-what-is-faster

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The performance difference is negligible. The && operator won't check the right hand expression when the left hand expression evaluates false. However, the & operator will check both regardless, maybe your confusion is caused by this fact.

In this particular example, I'd just choose the one using &&, since that's better readable.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...