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()
}
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()
}
The question is a non-issue, because:
I would recommend to:
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.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:
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
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!