Skip to content

Instantly share code, notes, and snippets.

@w0rm
Last active August 27, 2018 19:40
Show Gist options
  • Save w0rm/00c5236cfdf645df5656c3e680fd2da6 to your computer and use it in GitHub Desktop.
Save w0rm/00c5236cfdf645df5656c3e680fd2da6 to your computer and use it in GitHub Desktop.
Buffer construction (https://jsbench.github.io/#00c5236cfdf645df5656c3e680fd2da6) #jsbench #jsperf
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>Buffer construction</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 n = 10000;
const o = [];
for (let i=0;i<n;i++) {
o.push({ x: i, y: i + 1, z: i + 2});
}
const t = [];
for (let i=0;i<n;i++) {
t.push(new Float32Array([i, i + 1, i + 2]));
}
function P(x, y, z) {
this.x = x;
this.y = y;
this.z = z;
}
const c = [];
for (let i=0;i<n;i++) {
c.push(new P(i, i + 1, i + 2));
}
const a = [];
for (let i=0;i<n;i++) {
a.push([i, i + 1, i + 2]);
}
};
suite.add("literal object", function () {
// literal object
const ob = new Float32Array(n * 3);
for (let i = 0; i < n; i++) {
ob[i*3] = o[i].x;
ob[i*3 + 1] = o[i].y;
ob[i*3 + 2] = o[i].z;
}
});
suite.add("typed array", function () {
// typed array
const tb = new Float32Array(n * 3);
for (let i = 0; i < n; i++) {
for(let j =0; j < 3; j++) {
tb[i*3 + j] = t[i][j];
}
}
});
suite.add("constructed object", function () {
// constructed object
const cb = new Float32Array(n * 3);
for (let i = 0; i < n; i++) {
cb[i*3] = c[i].x;
cb[i*3 + 1] = c[i].y;
cb[i*3 + 2] = c[i].z;
}
});
suite.add("regular array", function () {
// regular array
const ab = new Float32Array(n * 3);
for (let i = 0; i < n; i++) {
for(let j =0; j < 3; j++) {
ab[i*3 + j] = a[i][j];
}
}
});
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("Buffer construction");
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