Skip to content

Instantly share code, notes, and snippets.

@jridgewell
Created January 25, 2022 09:08
Show Gist options
  • Save jridgewell/c5efc58acd31b29a5c2a454fd35bff9c to your computer and use it in GitHub Desktop.
Save jridgewell/c5efc58acd31b29a5c2a454fd35bff9c to your computer and use it in GitHub Desktop.
new Array vs Int32Array.subarray (http://jsbench.github.io/#c5efc58acd31b29a5c2a454fd35bff9c) #jsbench #jsperf
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>new Array vs Int32Array.subarray</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 base = new Int32Array(5);
function randomize() {
base[0] = Math.random() * 100;
base[1] = Math.random() * 5;
base[2] = Math.random() * 5;
base[3] = Math.random() * 5;
base[4] = Math.random() * 5;
}
function toArray() {
if (base[1] === 0) {
return [base[0]];
}
if (base[4] === 0) {
return [base[0], base[1], base[2], base[3]];
}
return [base[0], base[1], base[2], base[3], base[4]];
}
function toSubArray() {
if (base[1] === 0) {
return base.subarray(0, 1);
}
if (base[4] === 0) {
return base.subarray(0, 4);
}
return base.subarray(0, 5);
}
};
suite.add("Array", function () {
// Array
randomize();
toArray();
});
suite.add("subarray", function () {
// subarray
randomize();
toSubArray();
});
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("new Array vs Int32Array.subarray");
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