forEach vs for(i => n)

Benchmark created on


Description

Testing which is more performant on large objects..

Preparation HTML

<div id="dataContainer" style="display: none;" />

<script>
const data = Array.from({ length: 50000 }, (v, i) => ({id: i + 1, num: i}));
// Convert data to JSON and store it in the div    

document.getElementById('dataContainer').textContent = JSON.stringify(data);
</script>

Setup

// Extract the data from the div
const rawData = document.getElementById('dataContainer').textContent;
const data = JSON.parse(rawData);

Test runner

Ready to run.

Testing in
TestOps/sec
anon forEach loop
total = 0;

data.forEach((_) => total += _.num)
ready
raw for loop
total = 0;
var i = 0;
for (let i = 0; i < data.length; i++) {
  total += data[i].num;
}
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.