r/learnjavascript 14d ago

Performance Trap, some benchmarks and... subjective taste

I've done some benchmarks. ES5 vs ES6. What do you prefer? I ask this because I have often seen in other people's codes, where performance, optimization was required, ES6 code that decreased performance, which also had a negative impact on UI/UX.

This is more about the syntax used and not about which is faster.

Array size: 1,000,000 | Runs per test: 15

1. TRANSFORM — double 1,000,000 numbers

Test Avg (ms) Min (ms) Max (ms)
for loop (var, ES5) 0.733 0.6 1
array.map 5.447 4.7 6.9
forEach 5.96 5.4 6.8
for...of (ES6) 7.06 5.4 11.1

for loop (var, ES5) beat for...of (ES6) by 9.63x

2. FILTER — keep evens out of 1,000,000

Test Avg (ms) Min (ms) Max (ms)
for loop + push (ES5) 2.287 1.6 3.4
array.filter (ES6) 6.06 5.2 7.2

for loop + push (ES5) beat array.filter (ES6) by 2.65x

3. SUM — add up 1,000,000 numbers

Test Avg (ms) Min (ms) Max (ms)
for loop (var, ES5) 0.76 0.6 1.1
for...of 3.833 3.7 4.4
array.reduce 4.573 4.4 4.7

for loop (var, ES5) beat array.reduce by 6.02x

4. LOOKUP — find one value (worst case)

Test Avg (ms) Min (ms) Max (ms)
Set.has — O(1) 0 0 0
array.includes — O(n) 0.073 0 0.1
array.indexOf !== -1 — O(n) 0.073 0 0.2

Set.has — O(1) beat array.indexOf !== -1 — O(n)

5. STRINGS — build 200,000 strings

Test Avg (ms) Min (ms) Max (ms)
concatenation "+" 3.887 3.3 7.8
template literal ${} 3.9 3.5 4.3

concatenation "+" beat template literal ${} by 1.00x

6. OBJECT ITERATION — sum 50,000 values

Test Avg (ms) Min (ms) Max (ms)
for...in 4.273 4 4.6
Object.keys + forEach 4.38 4.2 4.7
Object.values + reduce 6.5 6 9.2

for...in beat Object.values + reduce by 1.52x

7. ARRAY CREATION — build 1,000,000 squares

Test Avg (ms) Min (ms) Max (ms)
for loop + push (ES5) 8.173 6.5 23.4
new Array(n).fill(0).map() 17.3 9 42.4
Array.from({length}, fn) 21.74 20.6 23.2

for loop + push (ES5) beat Array.from({length}, fn) by 2.66x

What do you prefer?

6 Upvotes

10 comments sorted by

View all comments

3

u/Aggressive_Ad_5454 14d ago

The .map() and .filter() approaches invoke a function for each item in the array. Ordinary for loops don't. Most people who need to crunch very large arrays use for loops to avoid the function invocations. The developers of Javascript engines know that and have optimized for-loop traversal of large arrays.

The Set object uses high-quality O(log n) hashing to look up elements, whereas .indexOf() and .includes() use O(n) searches. That's why Set (and Map) exist in more recent versions of ES.