function compareEndsWith(val, comparator) {
return val.endsWith(comparator)
}
function compareSliceMethod(val, comparator) {
const thingToCompare = val.slice(-comparator.length)
return thingToCompare === comparator
}
const value = Math.random().toString().padEnd(20,'0');
const ending = "asdf"
compareEndsWith(value, ending)
const value = Math.random().toString().padEnd(20,'0');
const ending = "asdf"
compareSliceMethod(value, ending)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
endWith | |
slice |
Test name | Executions per second |
---|---|
endWith | 491714.7 Ops/sec |
slice | 578069.6 Ops/sec |
I'd be happy to help you understand the JavaScript benchmark on MeasureThat.net.
Benchmark Overview
The benchmark compares two ways to check if a string ends with a specific suffix: string.endsWith()
and string.slice() + ===
. The benchmark is designed to measure which approach is faster, more efficient, and possibly more accurate for this specific use case.
Options Compared
Two options are compared:
string.endsWith(comparator)
: This method checks if the string ends with the specified suffix (comparator
).string.slice(-comparator.length) === comparator
: This approach uses the slice()
method to extract a substring from the end of the original string, and then compares it directly to the comparator using the ===
operator.Pros and Cons
Library
There is no library explicitly mentioned in this benchmark. However, string.endsWith()
is an intrinsic JavaScript method that's implemented by most modern browsers and Node.js environments.
Special JS Feature or Syntax
This benchmark does not use any special JavaScript features or syntax beyond what's standard in JavaScript (ECMAScript).
Benchmark Preparation Code
The preparation code defines two functions:
compareEndsWith(val, comparator)
: This function checks if the string val
ends with the specified suffix (comparator
) using the endsWith()
method.compareSliceMethod(val, comparator)
: This function uses the slice()
method to extract a substring from the end of the original string and compares it directly to the comparator using the ===
operator.Other Alternatives
In theory, other approaches could be used to check if a string ends with a specific suffix, such as:
RegExp.prototype.test(val, new RegExp(
^.*${comparator}$, 'g'))
However, these alternatives are not part of the benchmark and may not be as efficient, readable, or maintainable as the two options being compared.
I hope this explanation helps! Let me know if you have any further questions.