Reputation: 6301
I'm coming from C# and there it's a huge different between
A:
var stringVal = "1";
switch (stringVal)
{
case "0" :
break;
case "1" :
break;
}
and
B:
var intVal = 1;
switch (intVal)
{
case 0 :
break;
case 1 :
break;
}
B is much faster in C# (cause the String-Switch will converted to if-else-structure from the compiler).
Is it in JavaScript similar? (Of course there is just the number-type in JS)
And - for readability - if i want to use it with some enum-"equivalent" in JS (like described here http://stijndewitt.com/2014/01/26/enums-in-javascript/), is there a anyway performance-improvement when using
var caseEnum = {
firstCase : 0,
secCase : 1
}
var enumVal = caseEnum.secCase ;
switch (enumVal )
{
case caseEnum.firstCase :
break;
case caseEnum.secCase :
break;
}
?
(I know that i could do it with object literals, but the switch-statement with integer is more naturally for me)
Upvotes: 4
Views: 1863
Reputation: 6301
I did a little incredible ugly Test on my own
( look at:
https://jsfiddle.net/PutziSan/kzdwt8u2 )
and run the code on different browsers (results below), (all the browsers was updated on the latest version today - 03.01.2016)
by the way another hint, that edge and IE is just ridiculous.
The results are realy interesting, i guess.
(I know this sort of "tests" are not that accurate, but i think they can give a hint)
It seems, that switch with Integer is noticed from the compilers, but it has not that great impact.
Upvotes: 4
Reputation: 141986
Is it in JavaScript similar? (Of course there is just the number-type in JS)
In javascript the expression can be almost anything, its not like in C
where the type is verified during compilation, here its being calculated during "runtime"
That's the main difference.
A very detailed explanation is in the MDN - Switch
... expression evaluates to the same value as the result of the input expression
(using strict comparison, ===)
... is there a anyway performance-improvement
It depends on your browser and its JS engine.
Upvotes: 0