<div></div>
window.regex = /^test/;
window.match = 'test';
var data = window.data = [];
const possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
var TOTAL_STRINGS = window.TOTAL_STRINGS = 100000;
function getRandomInt(max) {
return Math.floor(Math.random() * max);
}
function makeRandomString(len) {
var text = "";
for( var i=0; i < len; i++ ) {
text += possible.charAt(getRandomInt(possible.length));
}
return text;
}
while (data.length < TOTAL_STRINGS) {
data.push(makeRandomString(getRandomInt(20)));
}
var x = 0;
var TOTAL_STRINGS = window.TOTAL_STRINGS;
var data = window.data;
var regex = window.regex;
while (x < TOTAL_STRINGS) {
const str = data[x];
regex.test(str);
x += 1;
}
var x = 0;
var TOTAL_STRINGS = window.TOTAL_STRINGS;
var data = window.data;
var match = window.match;
while (x < TOTAL_STRINGS) {
const str = data[x];
str.indexOf(match) === 0;
x += 1;
}
var x = 0;
var TOTAL_STRINGS = window.TOTAL_STRINGS;
var data = window.data;
var match = window.match;
while (x < TOTAL_STRINGS) {
const str = data[x];
str.includes(match);
x += 1;
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Regex | |
.indexOf | |
.includes |
Test name | Executions per second |
---|---|
Regex | 877.7 Ops/sec |
.indexOf | 21938.5 Ops/sec |
.includes | 22024.8 Ops/sec |
Measuring the performance of different JavaScript methods for string matching is a crucial task, and MeasureThat.net provides a valuable platform for benchmarking.
The provided JSON represents a benchmark test that compares three popular JavaScript string matching methods:
Let's dive into the details of each approach:
Regex
Regex is a powerful pattern-matching method that allows you to search for patterns in strings. It's widely used in many programming languages, including JavaScript.
Pros:
Cons:
.indexOf
IndexOf is a simple method that finds the index of a specific value within a string.
Pros:
Cons:
.includes
Includes is similar to .indexOf but returns true
if the value is found anywhere in the string.
Pros:
Cons:
Now, let's consider other alternatives that could have been used instead of these three methods:
In this benchmark, the test users special JS features and syntax, such as regular expressions (Regex). The window.regex
variable is defined in the Script Preparation Code section, which allows the tests to use it throughout the benchmark.