Skip to content

Instantly share code, notes, and snippets.

@JobLeonard
Last active June 28, 2017 16:14
Show Gist options
  • Save JobLeonard/a5c234621b81cd41b26e31d7f92f62d4 to your computer and use it in GitHub Desktop.
Save JobLeonard/a5c234621b81cd41b26e31d7f92f62d4 to your computer and use it in GitHub Desktop.
charAt vs charCodeAt hashmap #jsbench #jsperf (http://jsbench.github.io/#a5c234621b81cd41b26e31d7f92f62d4) #jsbench #jsperf
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>charAt vs charCodeAt hashmap #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 () {
var base64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
var charDict = (function (){
var dict = {};
for (var i = 0; i < base64.length; i++){
dict[base64.charAt(i)] = i;
}
return dict;
})();
var charCodeDict = (function () {
var dict = {};
for (var i = 0; i < base64.length; i++){
dict[base64.charCodeAt(i)] = i;
}
return dict;
})();
var randomString = (function (){
var i = 100000, strArray = new Array(i);
while(i--){
strArray[i] = base64.charAt(Math.random(base64.length)|0);
}
return strArray.join('');
})();
var converted = 0
};
suite.add("charDict", function () {
// charDict
for (var i = 0; i < randomString.length; i++){
converted = charDict[randomString.charAt(i)];
}
});
suite.add("charCodeDict", function () {
// charCodeDict
for (var i = 0; i < randomString.length; i++){
converted = charCodeDict[randomString.charCodeAt(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("charAt vs charCodeAt hashmap #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