Skip to content

Instantly share code, notes, and snippets.

@jridgewell
Last active January 25, 2020 08:30
Show Gist options
  • Select an option

  • Save jridgewell/f5a12ed2e457ae2f8b9a874736e54ee0 to your computer and use it in GitHub Desktop.

Select an option

Save jridgewell/f5a12ed2e457ae2f8b9a874736e54ee0 to your computer and use it in GitHub Desktop.
Fastest limited size lookup of integers (base64 lookup) #jsbench #jsperf (https://jsbench.github.io/#f5a12ed2e457ae2f8b9a874736e54ee0) #jsbench #jsperf
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>Fastest limited size lookup of integers (base64 lookup) #jsbench #jsperf</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 chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
const regularObject = {};
const nullObject = Object.create(null);
const array = [];
const typedArray = new Uint8Array(123);
for (let i = 0; i < 123; i++) array[i] = 0;
for (let i = 0; i < chars.length; i++) {
const code = chars.charCodeAt(i);
regularObject[code] = i;
nullObject[code] = i;
array[code] = i;
typedArray[code] = i;
}
function regularObjectMap() {
let total = 0;
for (let i = chars.length - 1; i >= 0; i--) {
total += regularObject[chars.charCodeAt(i)]
}
return total;
}
function nullObjectMap() {
let total = 0;
for (let i = chars.length - 1; i >= 0; i--) {
total += nullObject[chars.charCodeAt(i)]
}
return total;
}
function arrayLookup() {
let total = 0;
for (let i = chars.length - 1; i >= 0; i--) {
total += array[chars.charCodeAt(i)]
}
return total;
}
function typedArrayLookup() {
let total = 0;
for (let i = chars.length - 1; i >= 0; i--) {
total += typedArray[chars.charCodeAt(i)]
}
return total;
}
};
suite.add("regularObjectMap();", function () {
regularObjectMap();
});
suite.add("nullObjectMap();", function () {
nullObjectMap();
});
suite.add("arrayLookup();", function () {
arrayLookup();
});
suite.add("typedArrayLookup();", function () {
typedArrayLookup();
});
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("Fastest limited size lookup of integers (base64 lookup) #jsbench #jsperf");
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