Skip to content

Instantly share code, notes, and snippets.

@JenieX
Forked from jcunews/for_vs_forEach.html
Created May 25, 2022 02:13
Show Gist options
  • Save JenieX/8137b03ceb7e074ff7b9f0dae339ce8d to your computer and use it in GitHub Desktop.
Save JenieX/8137b03ceb7e074ff7b9f0dae339ce8d to your computer and use it in GitHub Desktop.
Simple performance test comparison between `for` and `forEach()` loop. Both loops enumerates an array of 50,000,000 elements for 10 times.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>for vs forEach</title>
<style>
.columns {
column-count: 2;
}
.report {
margin-top: .5em;
height: 16em;
overflow-y: scroll;
background-color: #eee;
white-space: pre;
}
.buttons {
margin-top: .5em;
text-align: center;
}
</style>
<script>
addEventListener("load", function(arr, loopLength, loopCount, times, timesNext, count) {
loopLength = 50000000;
loopCount = 10;
arr = [];
arr.length = loopLength;
times = [];
times.length = loopCount;
function avgTime() {
var sum, i;
sum = 0;
for (i = 0; i < loopCount; i++) sum += times[i];
return (sum / loopCount).toFixed(0);
}
function runFor() {
var a, value, i;
for (i = 0; i < loopLength; i++) {
//instruction to emulate `value` argument of forEach's callback
value = arr[i];
//dummy instruction payload
a = value;
}
}
function runForEach() {
var a;
arr.forEach(function(value) {
//dummy instruction payload
a = value;
});
}
function runTestFor() {
var timeStart, timeEnd, timeSpan;
if (count--) {
timeStart = (new Date()).getTime();
runFor();
timeEnd = (new Date()).getTime();
timeSpan = timeEnd - timeStart;
times[++timesNext] = timeSpan;
rfor.textContent += "\n" + timeSpan + "ms";
rfor.scrollBy(0, 99);
setTimeout(runTestFor, 0);
} else {
rfor.textContent += "\ndone. " + avgTime() + "ms average.";
rfor.scrollBy(0, 99);
count = loopCount;
timesNext = -1;
runTestForEach();
}
}
function runTestForEach() {
var timeStart, timeEnd, timeSpan;
if (count--) {
timeStart = (new Date()).getTime();
runForEach();
timeEnd = (new Date()).getTime();
timeSpan = timeEnd - timeStart;
times[++timesNext] = timeSpan;
rforeach.textContent += "\n" + timeSpan + "ms";
rforeach.scrollBy(0, 99);
setTimeout(runTestForEach, 0);
} else {
rforeach.textContent += "\ndone. " + avgTime() + "ms average.";
rforeach.scrollBy(0, 99);
btn.disabled = false;
}
}
btn.onclick = function() {
btn.disabled = true;
count = loopCount;
timesNext = -1;
runTestFor();
};
});
</script>
</head>
<body>
<div class="columns">
<div class="column">
for loop
<div id="rfor" class="report">ready</div>
</div>
<div class="column">
forEach loop
<div id="rforeach" class="report">ready</div>
</div>
</div>
<div class="buttons">
<button id="btn">Start</button>
</div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment