Skip to content

Instantly share code, notes, and snippets.

@eanplatter
Created February 25, 2019 17:03
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 eanplatter/c5c95dd2ea81c10feb7765b385b6b5e4 to your computer and use it in GitHub Desktop.
Save eanplatter/c5c95dd2ea81c10feb7765b385b6b5e4 to your computer and use it in GitHub Desktop.
Loop vs forEach vs recursion (https://jsbench.github.io/#c5c95dd2ea81c10feb7765b385b6b5e4) #jsbench #jsperf
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>Loop vs forEach vs recursion</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;
suite.add("const a = {foo: 'bar'}", function () {
const a = {foo: 'bar'}
const b = {bar: 'baz'}
const c = {baz: 'foo'}
const arr = [a,c,a,b,{foo: 'bar'}, {bar: 'baz'}, {baz: 'foo'},1,2,3]
function uniquifyArr(arr) {
let arrSet = []
for (let i = 0; i < arr.length; i++) {
if (!arrSet.includes(arr[i]))
arrSet.push(arr[i])
}
return arrSet
}
uniquifyArr(arr)
});
suite.add("const a = {foo: 'bar'}", function () {
const a = {foo: 'bar'}
const b = {bar: 'baz'}
const c = {baz: 'foo'}
const arr = [a,c,a,b,{foo: 'bar'}, {bar: 'baz'}, {baz: 'foo'},1,2,3]
function uniquifyArr(arr) {
let arrSet = []
arr.forEach(n => !arrSet.includes(n) && arrSet.push(n))
return arrSet
}
uniquifyArr(arr)
});
suite.add("const a = {foo: 'bar'}", function () {
const a = {foo: 'bar'}
const b = {bar: 'baz'}
const c = {baz: 'foo'}
const arr = [a,c,a,b,{foo: 'bar'}, {bar: 'baz'}, {baz: 'foo'},1,2,3]
function uniquifyArr(arr, set) {
if (arr.length < 1)
return set
arr.splice(0, 1)
if (set.includes(arr[0]))
return uniquifyArr(arr, set)
return uniquifyArr(arr, set.concat(arr[0]))
}
uniquifyArr(arr, [])
});
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("Loop vs forEach vs recursion");
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