var example = 'there is no spoon'
var result = example.slice(10)
var result = example.substr(10)
var result = example.substring(10)
var result = example
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
slice | |
substr | |
substring | |
Nop |
Test name | Executions per second |
---|---|
slice | 503419872.0 Ops/sec |
substr | 62158564.0 Ops/sec |
substring | 508300992.0 Ops/sec |
Nop | 517870176.0 Ops/sec |
This benchmark from MeasureThat.net compares three string manipulation methods in JavaScript: slice
, substr
, and substring
, as well as a “no operation” (Nop) case where the string is simply assigned without manipulation. Each method is tested in terms of performance, specifically how many times they can be executed per second on the given system (Safari 18 on macOS).
slice:
string.slice(startIndex)
startIndex
and the end of the string.substr:
string.substr(startIndex)
startIndex
and continuing until the end of the string.substring:
string.substring(startIndex)
slice
, but does not accept negative indices.Nop:
result
, it establishes a benchmark for the simplest case without string manipulation.From the benchmark results, we can see how each method performed in terms of executions per second:
Nop
has the highest execution rate since it performs no computation.substring
and slice
are very close in terms of performance, while substr
significantly lags behind.substring
and slice
is not substantial, indicating both are optimized well in the underlying JavaScript engine in Safari.substr
, being deprecated, suggests engineers may want to avoid it in favor of the other two methods.substr
: Since this function is deprecated, it is advisable for developers to refrain from using it in new code. Instead, using slice
or substring
can enhance code maintainability and compatibility with future JavaScript standards.slice
to handle negative indices may be a decisive factor for developers who require flexibility in string manipulation.In addition to these string manipulation methods, there are other approaches for handling strings in JavaScript:
When deciding which method to use, software engineers should consider readability, performance, and future compatibility in their codebases.