const site = "archive.test.org";
const regex = new RegExp("https?:\/\/" + site + "\/");
for (let k = 0; k < 10000; k++) {
"https://archive.test.org/board/".replace(regex, "");
}
const site = "archive.test.org";
for (let k = 0; k < 10000; k++) {
"https://archive.test.org/board/".replace("https://", "").replace("http://", "").replace(site).replace("/");
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
regex | |
multiple replaces |
Test name | Executions per second |
---|---|
regex | 2566.7 Ops/sec |
multiple replaces | 653.0 Ops/sec |
I'd be happy to explain what's being tested in the provided benchmark.
The benchmark compares two approaches to replace multiple substrings in a string: using a regular expression (regex) and using multiple separate replace()
calls.
Option 1: Regex
In this approach, a regex pattern is created to match the target strings (https://
and /
) followed by the specific site URL. The pattern uses character classes and anchors to ensure only full matches are found. The regex is then used in a for
loop to replace the matched substrings with an empty string.
Pros:
Cons:
Option 2: Multiple Replaces
In this approach, multiple replace()
calls are used sequentially to replace each target substring individually.
const site = "archive.test.org";
let result = "https://archive.test.org/board/";
result = result.replace("http://", "");
result = result.replace(site, "");
result = result.replace("/", "");
console.log(result);
Pros:
Cons:
The benchmark provides results for both approaches on different browsers and devices, allowing users to compare performance across these factors.
As for other alternatives, some may consider using native JavaScript methods, such as String.prototype.replace()
or RegExp.prototype.test()
, but these would likely result in similar performance to the regex approach.