Skip to content

Instantly share code, notes, and snippets.

@bmaupin
Last active January 13, 2018 17:58
Show Gist options
  • Save bmaupin/8ed37bb81a337674e317ab5625c701ea to your computer and use it in GitHub Desktop.
Save bmaupin/8ed37bb81a337674e317ab5625c701ea to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>Array iteration</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 () {
let array = [1, 2, 4 , 5, 66, 38, 39, 3993, 33, "test", "hello", 93, 93, 20, 77, "hu", 92, 18, 4 , 5, 66, 38, 39, 3993, 33, "test", "hello", 93, 93, 20, 77, "hu", 92, 18, 4 , 5, 66, 38, 39, 3993, 33, "test", "hello", 93, 93, 20, 77, "hu", 92, 18, 4 , 5, 66, 38, 39, 3993, 33, "test", "hello", 93, 93, 20, 77, "hu", 92, 18, 4 , 5, 66, 38, 39, 3993, 33, "test", "hello", 93, 93, 20, 77, "hu", 92, 18, 4 , 5, 66, 38, 39, 3993, 33, "test", "hello", 93, 93, 20, 77, "hu", 92, 18];
let item;
};
suite.add("Simple for loop", function () {
// Simple for loop
for (let i = 0; i < array.length; i++) {
item = array[i];
}
});
suite.add("For loop with cached index", function () {
// For loop with cached index
for (let i = 0, len=array.length; i < len; i++) {
item = array[i];
}
});
suite.add("forEach", function () {
// forEach
array.forEach(element => {
item = element;
});
});
suite.add("for..of", function () {
// for..of
for (let element of array) {
item = element;
}
});
suite.add("NOTE: for..in is not guaranteed to respect the order of the array and so shouldn't be used.", function () {
// NOTE: for..in is not guaranteed to respect the order of the array and so shouldn't be used.
// (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in#Array_iteration_and_for...in)
// for..in
for (let i in array) {
item = 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("Array iteration");
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