var string = 'test.ts';
var stringToCheck = 'cfdsfdsffdsfs.test.ts';
var string2ToCheck = 'jfkdsljfdkslfjds.test.ts';
var result = null;
var result2 = null;
result = stringToCheck.endsWith(string);
result2 = string2ToCheck.endsWith(string);
result = stringToCheck.includes(string);
result2 = string2ToCheck.includes(string);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
.endsWith | |
.includes |
Test name | Executions per second |
---|---|
.endsWith | 1706731.4 Ops/sec |
.includes | 584810.1 Ops/sec |
This benchmark compares two JavaScript string methods: .endsWith
and .includes
. The benchmark aims to measure the performance of these methods when checking if a given string (in this case, a file name) is included at the end of, or anywhere within, another string.
.endsWith
Method:
true
if the string ends with the specified substring, and false
otherwise.result = stringToCheck.endsWith(string);
.includes
Method:
true
if found, and false
otherwise.result = stringToCheck.includes(string);
The dramatically higher performance of the .endsWith
method compared to the .includes
method indicates that, for cases where the requirement is simply to check if a string ends with a specific substring, it's preferable to use .endsWith
.
Use .includes
when a broader substring search is needed; however, developers should be aware that it might introduce overhead in performance-sensitive applications compared to .endsWith
.
In JavaScript, other string methods or techniques can be used depending on the requirements:
Regular Expressions:
IndexOf Method:
.includes
, string.indexOf(substring) !== -1
can still be used to check for the presence of a substring. However, it does not indicate where the substring is located and can be less performant compared to modern methods.Substring Comparison:
string.slice(-length)
and compare it directly. This can be more manual and may introduce additional complexity in code.This benchmark effectively illustrates the performance differences between .endsWith
and .includes
, guiding developers in making informed choices regarding string checks in their JavaScript code. For suffix verification, prefer .endsWith
, while for generalized substring checks, use .includes
, weighing the performance impacts as needed.