Skip to content

Instantly share code, notes, and snippets.

@cephalization
Forked from RubaXa/index.html
Created October 17, 2019 14:24
Show Gist options
  • Select an option

  • Save cephalization/835140d2ac680481e62951e641f6a5c4 to your computer and use it in GitHub Desktop.

Select an option

Save cephalization/835140d2ac680481e62951e641f6a5c4 to your computer and use it in GitHub Desktop.
for-in vs. Object.values vs. for loop (http://jsbench.github.io/#835140d2ac680481e62951e641f6a5c4) #jsbench #jsperf
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>for-in vs. Object.values vs. for loop</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 () {
var test = {
foo: 1,
bar: 2,
baz: 3,
qux: 4,
a: 5,
b: 6,
c: 7,
d: 8,
e: 9,
f: 10,
};
var testIds = Object.keys(test)
};
suite.add("for-in", function () {
/** for-in **/
var values = [];
for (var key in test) {
values.push(test[key]);
}
});
suite.add("for in + hasOwnProperty", function () {
/** for in + hasOwnProperty **/
var values = [];
for (var key in test) {
if (test.hasOwnProperty(key)) {
values.push(test[key]);
}
}
});
suite.add("Object.values", function () {
/** Object.values **/
var values = Object.values(test)
});
suite.add("for loop", function () {
/** for loop **/
var values = []
for (var i = 0; i < testIds.length; i++) {
values.push(test[testIds[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-in vs. Object.values vs. for loop");
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