Skip to content

Instantly share code, notes, and snippets.

@jridgewell
Created August 1, 2022 21:29
Show Gist options
  • Select an option

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

Select an option

Save jridgewell/0f971d52c8a86eb2c3e5983f5e8ebd0a to your computer and use it in GitHub Desktop.
String.replace vs RegExp.exec loop (https://jsbench.github.io/#0f971d52c8a86eb2c3e5983f5e8ebd0a) #jsbench #jsperf
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>String.replace vs RegExp.exec loop</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 re = /```(?:(?!```)[^])*|<http[^|]*|\|http[^>]*|(\bVercel\b|\bNextJS\b)/gi;
const short = "Vercel is awesome.";
const long = short.repeat(100);
function replace(text, re) {
return text.replace(re, (match, term) => {
if (term) return `*${term}*`;
return match;
});
}
const replacer = (match, term) => {
if (term) return `*${term}*`;
return match;
};
function replaceExtracted(text, re) {
return text.replace(re, replacer);
}
function whileExec(text, re) {
let match;
let str = '';
let idx = 0;
while ((match = re.exec(text))) {
const term = match[1];
if (term) {
str += text.slice(idx, match.index);
str += `*${term}*`;
idx = match.index + match[0].length;
continue;
}
}
return str + text.slice(idx);
}
};
suite.add("replace(short, re);", function () {
replace(short, re);
});
suite.add("replaceExtracted(short, re);", function () {
replaceExtracted(short, re);
});
suite.add("whileExec(short, re);", function () {
whileExec(short, re);
});
suite.add("replace(long, re);", function () {
replace(long, re);
});
suite.add("replaceExtracted(long, re);", function () {
replaceExtracted(long, re);
});
suite.add("whileExec(long, re);", function () {
whileExec(long, re);
});
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("String.replace vs RegExp.exec loop");
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