const value = "douche nation"
const ending = "tion"
function compareEndsWith(val, comparator) {
return val.endsWith(comparator)
}
function compareSliceMethod(val, comparator) {
const thingToCompare = val.slice(-comparator.length)
return thingToCompare === comparator
}
const value = "douche nation"
const ending = "tion"
compareEndsWith(value, ending)
const value = "douche nation"
const ending = "tion"
compareSliceMethod(value, ending)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
endWith | |
slice |
Test name | Executions per second |
---|---|
endWith | 97852408.0 Ops/sec |
slice | 186108464.0 Ops/sec |
I'll dive into explaining the benchmark.
What is tested:
The provided benchmark tests two approaches for checking if a string ends with a certain substring:
endsWith
: A method that checks if a string ends with another string using the String.prototype.endsWith()
method.slice
and triple equal (
): An approach that uses the slice()
method to extract the last few characters of the string, compares them using triple equals (===
) with the target substring.Options compared:
The benchmark compares the performance of:
endsWith
slice
and triple equal
Pros and Cons:
Library and purpose:
In this benchmark, the slice()
method is used, which is a built-in JavaScript method. The slice()
method takes two arguments: the start index and the end index. In this case, the end index is calculated using the length of the target substring (-comparator.length
).
Special JS feature or syntax:
There are no special features or syntax used in this benchmark.
Other alternatives:
Alternative approaches for checking if a string ends with another string include:
/endsWith/g
): This method is more efficient than endsWith
but may be slower for very long strings.lastIndexOf()
method: This method returns the index of the last occurrence of the target substring, which can be used to determine if the string ends with it.For example:
function compareLastIndexOf(val, comparator) {
return val.lastIndexOf(comparator) === val.length - comparator.length;
}
However, these alternatives are not tested in this benchmark.