var test = 'test'
switch(test) {
case 'test1':
return true;
default:
return false;
}
if (test === 'test1') {
return true;
} else {
return false;
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
switch | |
if/else if |
Test name | Executions per second |
---|---|
switch | 151406928.0 Ops/sec |
if/else if | 142211296.0 Ops/sec |
The benchmark "JS switch vs if/else if 1 condition" aims to compare the performance of two different conditional branching methods in JavaScript: the switch
statement versus the traditional if/else if
construct.
Switch Statement:
switch(test) {
case 'test1':
return true;
default:
return false;
}
If/Else If Statement:
if (test === 'test1') {
return true;
} else {
return false;
}
Switch Statement:
If/Else If Statement:
The tests were executed in Chrome 131 on a Windows platform. The results showed:
From these results, the switch
statement performed better in terms of execution speed compared to the if/else if
statement for this specific case.
switch
and if/else if
statements is using an object to store possible values and their corresponding results. This can improve readability and performance in certain situations.const switchObj = {
'test1': true
};
return switchObj[test] || false;
Overall, depending on the specific use case, each approach has its merits and considerations. Selecting the best one requires a balance between performance needs and code maintainability.