vendredi 10 avril 2020

Which is more efficient Ternary operator or one-line IF?

I'm in the middle of rewriting a python code to nodejs and I'm wondering which is more efficient:

a = func1()
a = a ? a : func2()

or

a = func1()
if (!a) a = func2()

Originally, I was writing the first block as:

a = func1() ? func1() : func2()

but I think this would ultimately call func1() twice, hence assigning it first to a variable.

NOTE: I accidentally posted this on ServerFault. Thanks to cyberx86 (https://serverfault.com/users/86472/cyberx86) for pointing this out and saying performance is negligible. And also making a suggestion:

a = func1() || func2()

Aucun commentaire:

Enregistrer un commentaire