Sign in
Log inSign up

Fastest code in javascript.

biplab malakar's photo
biplab malakar
·Apr 20, 2018

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.

  1. 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.

ifelse.jpg For a large number of conditions switch is faster than if-else.

ifelse1.jpg

  1. 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.

if-ternary.jpg

  1. Map vas forEach: Map is always faster then forEach.

mab-each.jpg

  1. 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.

for-reduce.jpg

  1. Filter vs For Loop: Try to find element those are 1. And the filter is faster than For Loop

filter-for.jpg

Note: All the details are given based on the result of jspref jsperf.com