Naive string matcher while vs for loop

Benchmark created on


Description

Test the performance on implementing naive string matching algorithm with while loop vs for loop

Setup

let text = "AAGAGAGAGAAGAG";
let pattern = "Aagag";

// for case insensitive search
text = text.toUpperCase();
pattern = pattern.toUpperCase();

let count = 0;
const textLength = text.length;
const patternLength = pattern.length;

Test runner

Ready to run.

Testing in
TestOps/sec
Naive for loop
for (let i = 0; i <= textLength - patternLength; i++)
{
	for (let j = 0; j < patternLength; j++)
	{
		if (text[i + j] !== pattern[j]) break;
		if (j === patternLength - 1) count++;
	}
}
return count;
ready
Naive while loop
for (i = 0; i <= textLength - patternLength; i++)
{
	let j = 0;
	while (j < patternLength && text[i + j] == pattern[j])
	{
		j++;
	}
	if (j === patternLength) count++;
}
return count;
ready

Revisions

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