String Search (v2)

Revision 2 of this benchmark created on


Setup

const testString = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Morbi mattis ullamcorper velit sed ullamcorper.";

// For counting matches
let matchCount = 0;

Test runner

Ready to run.

Testing in
TestOps/sec
Method 1: Regex with match()
// Reset
matchCount = 0;

// Execute
const matches = testString.match(/m/g);
matchCount = matches ? matches.length : 0
ready
Method 2: Char by Char (for loop)
// Reset
matchCount = 0;

// Execute
for (let i = 0; i < testString.length; i++) {
    if (testString[i] === 'm') {
        matchCount++;
    }
}
ready
Method 3: charAt() Loop
// Reset
matchCount = 0;

// Execute
for (let i = 0; i < testString.length; i++) {
    if (testString.charAt(i) === 'm') {
        matchCount++;
    }
}
ready
Method 4: Array.from + filter
// Reset
matchCount = 0;

// Execute
const chars = Array.from(testString);
matchCount = chars.map((char, index) => char === 'm' ? index : -1)
                .filter(index => index !== -1).length;
ready
Method 5: indexOf loop
// Reset
matchCount = 0;


// Execute
let index = testString.indexOf('m');
while (index !== -1) {
    matchCount++;
    index = testString.indexOf('m', index + 1);
}
ready
Method 6: Regex exec() loop
// Reset
matchCount = 0;

// Execute
const regex = /m/g;
let match;
while ((match = regex.exec(testString)) !== null) {
    matchCount++;
}
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.