var string = 'test.ts';
var stringToCheck = 'cfdsfdsffdsfs.test.ts';
var result = null;
result = stringToCheck.endsWith(string);
result = stringToCheck.includes(string);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
.endsWith | |
.includes |
Test name | Executions per second |
---|---|
.endsWith | 12297714.0 Ops/sec |
.includes | 9345396.0 Ops/sec |
The benchmark you provided tests two string methods in JavaScript: .endsWith()
and .includes()
, focusing specifically on their performance when applied to a string representing a filename.
.endsWith():
stringToCheck
(i.e., 'cfdsfdsffdsfs.test.ts'
) ends with the filename string ('test.ts'
)..endsWith()
executed at approximately 12.3 million operations per second..includes():
stringToCheck
contains the substring string
(i.e., 'test.ts'
)..includes()
executed at around 9.3 million operations per second..endsWith()
, as it can check for the presence of the substring anywhere within the string..substring() or .slice():
.endsWith()
, one could manually slice the string and compare it with the specified substring. This could add complexity and likely not perform as well as the native method.Regular Expressions:
/test\.ts$/
) can achieve similar results to both methods. However, regex can introduce additional overhead and complexity compared to the simpler string methods.Performance Considerations:
.endsWith()
is preferred for performance. If searching for a substring is needed, .includes()
is the better choice, despite being slower in this benchmark.The choice of string methods in JavaScript can significantly affect performance, as demonstrated in this benchmark between .endsWith()
and .includes()
. While both methods have their unique strengths and weaknesses, selecting the appropriate method based on the specific use case can lead to improved efficiency in code execution.