Skip to content

Instantly share code, notes, and snippets.

@jridgewell
Created January 25, 2020 08:13
Show Gist options
  • Select an option

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

Select an option

Save jridgewell/6545ad45e9ba2802d2b89feda4213a28 to your computer and use it in GitHub Desktop.
Looping over a string (https://jsbench.github.io/#6545ad45e9ba2802d2b89feda4213a28) #jsbench #jsperf
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>Looping over a string</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 short = 'testz';
const medium = 'test'.repeat(20) + 'z';
const long = 'test'.repeat(100) + 'z';
function forLoop(str) {
for (let i = 0; i < str.length; i++) {
if (str[i] === 'z') {
return true;
}
}
return false;
}
function forOfLoop(str) {
for (const char of str) {
if (char === 'z') {
return true;
}
}
return false;
}
class StringCharIterator {
constructor(string) {
this._string = string;
this._position = 0;
}
next() {
return this._string.charAt(this._position++);
}
peek() {
return this._string.charAt(this._position);
}
hasNext() {
return this._position < this._string.length;
}
}
function iteratorThing(str) {
const iterator = new StringCharIterator(str);
while (true) {
if (!iterator.hasNext()) break;
if (iterator.next() === 'z') {
return true;
}
}
return false;
}
};
suite.add("forLoop(short);", function () {
forLoop(short);
});
suite.add("forOfLoop(short);", function () {
forOfLoop(short);
});
suite.add("iteratorThing(short);", function () {
iteratorThing(short);
});
suite.add("forLoop(medium);", function () {
forLoop(medium);
});
suite.add("forOfLoop(medium);", function () {
forOfLoop(medium);
});
suite.add("iteratorThing(medium);", function () {
iteratorThing(medium);
});
suite.add("forLoop(long);", function () {
forLoop(long);
});
suite.add("forOfLoop(long);", function () {
forOfLoop(long);
});
suite.add("iteratorThing(long);", function () {
iteratorThing(long);
});
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("Looping over a string");
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