Fastest code in javascript.
When we write code we always think which one fast and slow based on their execution time required. And for that, we spent a lot of time to decide which one should I use(like if-else and switch, if-else and ternary, map and forEach). I find out a very good tool for checking out performance which is "jsperf.com". Based on this tool I listing some comparison.
- If-else vs switch: switch is faster then if-else when you have a very large number of condition and for very few conditions like 1or2or3 if is faster.
For a large number of conditions switch is faster than if-else.
- Ternary vs if-else: No difference between them but if we have if-else-if than ternary is slower than if-else-if, but it is negligible.
- Map vas forEach: Map is always faster then forEach.
- Simple For loop and reduce: Calculate the sum of all elements using for loop and javascript reduce function. Reduce is faster than simple For Loop.
- Filter vs For Loop: Try to find element those are 1. And the filter is faster than For Loop
Note: All the details are given based on the result of jspref jsperf.com