-3

What will be the fastest way for the browser ? Is there any difference in speed between these bellow ?

var bool = true 

if (bool) do()

bool ? do() : null

switch (bool) {
  case true:
    do()
}
user15873596
  • 155
  • 1
  • 9

3 Answers3

1

The question is a non-issue, because:

  1. The answer may vary between web browsers, as there is no such thing as 'the' JavaScript engine.
  2. The answer may vary over time, as JavaScript engines are still under development.
  3. The answer may be overruled by the JavaScript engine's optimizing compiler rewriting your code.
  4. The answer may be overruled by a JavaScript minifier (if any) rewriting your code.
  5. Real-world performance issues typically arise from poor architecture, not from syntactic preferences.

I would recommend to:

  • Focus on writing readable, maintainable code. See also: rules of optimization.
  • Avoid switch (someBool) { case true: ... case false: ... }. Nobody does that. Just in case there is a performance penalty, then you are probably the first ever to discover it.
Ruud Helderman
  • 10,563
  • 1
  • 26
  • 45
-1

In my opinion, the comparison is not correct in this way

Each of these items has its own performance

for example:

The switch is not usually used for individual conditions

Condition if‍‍‍‍ is usually used for single-line and single-condition conditions

It is true that comparisons can sometimes be made between these cases But the efficiency of each must be considered in its specific situations

In general, to compare codes, you can use sites that do this or manually by calculating the time.

Sample site:

https://jsben.ch/

More sites:

https://www.google.com/search?q=javascript+benchmark+online

For manual testing and more details, I definitely suggest you follow the link below

How do you performance test JavaScript code?

Erfan Bahramali
  • 392
  • 3
  • 13
-2

This might be not the fish you are looking for. But I will give you a fishing rod to find your answer. Hopefully you won't blame me.

There is javascript function that you can call if front of your if (bool) do() like checks. Put this in front of that: let t0 = performance.now();. Then create a loop that executes your statements like 10.000 times. After that loop you then put this: let t1 = performance.now();. Finally use this code to see how long your if (bool) do()'s did take: console.log("It took " + (t1 - t0) + " milliseconds.")

Now you can do this little trick for your other checks and compare them! Let me know the results!

ITGuy1990
  • 93
  • 1
  • 9