3 ms·
https://jsben.ch/WCjjG https://jsben.ch/WCjjG Well, seems like it does matter. Using an array is 50% slower than using an object and that's slower than using a
by gfxgirl 6y ago
https://jsben.ch/WCjjG https://jsben.ch/WCjjG
Well, seems like it does matter. Using an array is 50% slower than using an object and that's slower than using a Set in Chrome. Even worse in Safari. In Firefox array wins but you need to use a static array.
I don't know all the rules of JS. Semantically declaring an array in the function itself creates a new array on every invocation. Of course the JS engine should be able to figure out it doesn't need to create a new array every call but apparently Firefox's JS engine doesn't do that.
Note: I'm making the assumption we're talking about JavaScript since the code looked like JavaScript to me. I get that in another language the results might be vastly different.
- thomasahle 6y ago> Well, seems like it does matter. Using an array is 50% slower than using an object and that's slower than using a Set in Chrome. A 50% difference doesn't mean it matter. Unless this runs in some inner loop, just use the simplest solution.
- gfxgirl 6y agoI agree that if the fast solution is 10x the code then maybe choose another solution. In this case all 6 solutions are basically the same amount of code. There's absolutely no reason to choose the slowest solution. 50% can easily be the difference between some VSCode extension making it sluggish vs not. Further, in my experience slow solutions will eventually come back to bite you. One I saw recenty. see if 2 arrays contain the same elements. The "simple" solution is sort copies of the arrays, concat them into strings, compare the strings. It looks simple but it's around 1000x slower than pretty much any normal but not 1 line solution. 1000x won't matter when you're testing your 5 element arrays in your unit test but it will matter then your users start using larger arrays.
- thomasahle 6y agoAt least in the blog post, the alternative solution has 10x the number of lines. Of course, if you benchmark and this turns out to be important, try to optimize it.
- d--b 6y agoAnd then it's a lot faster to use switch: https://jsben.ch/U6w7l https://jsben.ch/U6w7l
- gfxgirl 6y agoSurprisingly byOr wins on Safari
- mirekrusin 6y agoYou can do direct comparision, it's like 30x faster. There is cost of creating array, calling functions etc.