Skip to content

Instantly share code, notes, and snippets.

@Lodin
Last active March 4, 2020 10:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Lodin/b83e7f369a6f7c309a68bd87d7f5a1bd to your computer and use it in GitHub Desktop.
Save Lodin/b83e7f369a6f7c309a68bd87d7f5a1bd to your computer and use it in GitHub Desktop.
for each vs filter map #jsbench #jsperf (http://jsbench.github.io/#b83e7f369a6f7c309a68bd87d7f5a1bd) #jsbench #jsperf
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>for each vs filter map #jsbench #jsperf</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/benchmark/1.0.0/benchmark.min.js"></script>
<script src="./suite.js"></script>
</head>
<body>
<h1>Open the console to view the results</h1>
<h2><code>cmd + alt + j</code> or <code>ctrl + alt + j</code></h2>
</body>
</html>
"use strict";
(function (factory) {
if (typeof Benchmark !== "undefined") {
factory(Benchmark);
} else {
factory(require("benchmark"));
}
})(function (Benchmark) {
var suite = new Benchmark.Suite;
Benchmark.prototype.setup = function () {
const array = Array.from({length: 100000}, (_, i) => i % 4 === 0 ? `str${i}` : i * 45);
};
suite.add("const res = [];", function () {
const res = [];
array.forEach((el) => {
if (typeof el !== 'string') {
res.push({[el]: el});
}
});
});
suite.add("const res = array", function () {
const res = array
.filter(el => typeof el !== 'string')
.map(el => ({[el]: el}));
});
suite.add("const res = [];", function () {
const res = [];
for (let i = 0, len = array.length; i < len; i++) {
if (typeof array[i] !== 'string') {
res.push({[array[i]]: array[i]});
}
}
});
suite.on("cycle", function (evt) {
console.log(" - " + evt.target);
});
suite.on("complete", function (evt) {
console.log(new Array(30).join("-"));
var results = evt.currentTarget.sort(function (a, b) {
return b.hz - a.hz;
});
results.forEach(function (item) {
console.log((idx + 1) + ". " + item);
});
});
console.log("for each vs filter map #jsbench #jsperf");
console.log(new Array(30).join("-"));
suite.run();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment