for loop endsWith

Benchmark created by Narendra Yadala on


Description

Adding a simple for loop endsWith function and checking its performance against other options. The performance result is same independent of the length of the input string and the input suffix. So basically 'for-loop` endsWith is the fastest.

Test runner

Ready to run.

Testing in
TestOps/sec
indexOfEndsWith
function endsWith(str, suffix) {
  return str.indexOf(suffix, str.length - suffix.length) !== -1;
}
//Th input
endsWith('abcdefghijklm', 'lam') //false
endsWith('abcdefghijklm', 'klm') //true
ready
regexEndsWith
function endsWith(str, suffix, caseInsensitive) {
  return new RegExp(
  String(suffix).replace(/[$%()*+.?\[\\\]{|}]/g, "\\$&") + "$", caseInsensitive ? "i" : "").test(str);
}
endsWith('abcdefghijklm', 'lam') //false
endsWith('abcdefghijklm', 'klm') //true
ready
forLoopEndsWith
function endsWith(str, suffix) {
  for (var suffixLength = suffix.length - 1, stringLength = str.length - 1;
  suffixLength > -1; --suffixLength, --stringLength) {
    if (str.charAt(stringLength) === suffix.charAt(suffixLength)) continue;
    else return false;
  }
  return true;
}
endsWith('abcdefghijklm', 'lam') //false
endsWith('abcdefghijklm', 'klm') //true
ready

Revisions

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

  • Revision 1: published by Narendra Yadala on