var example = 'there is no spoon'
var result = example.slice(0, 10)
var result = example.substr(0, 10)
var result = example.substring(0, 10)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
slice | |
substr | |
substring |
Test name | Executions per second |
---|---|
slice | 164953008.0 Ops/sec |
substr | 164829728.0 Ops/sec |
substring | 152793520.0 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks!
The provided JSON represents a benchmark test created on MeasureThat.net, which compares the performance of three string manipulation methods in JavaScript: slice()
, substr()
, and substring()
.
What is tested?
These three methods are compared when used with only a start index. In other words, they are not used to extract a substring from another string or to get a specific part of an array. Instead, each method is called with the same input string ("there is no spoon"
), but with different starting indices.
Options compared:
slice()
substr()
substring()
Each option has its own strengths and weaknesses:
slice()
: This method returns a new string that includes all the characters from the original string, starting at the specified index (exclusive). It's generally faster than the other two methods because it doesn't need to check if the start index is within bounds.substr()
: This method also returns a new string with the specified length, but it stops when it reaches the end of the string. In this test case, it's slower than slice()
because it needs to check if the requested length is less than or equal to the remaining characters in the string.substring()
: This method returns a new string that includes all the characters from the original string, starting at the specified index (exclusive). It's similar to slice()
, but its performance might vary depending on the browser and JavaScript engine used.Pros and cons:
slice()
: Fastest because it doesn't need to check bounds.substring()
and substr()
: May be slower due to bounds checking or length limitations.Library and its purpose:
None of the methods use any external libraries in this test case. They are built-in JavaScript functions that operate on strings.
Special JS feature or syntax:
This benchmark doesn't use any special features or syntax beyond standard JavaScript methods. However, it's worth noting that some browsers might have variations or extensions of these methods (e.g., String.prototype.slice()
is not available in older browsers).
Other alternatives:
If you were to rewrite this benchmark, you could consider other string manipulation methods, such as:
RegExp
) to extract parts of a string.Array.prototype.slice()
, Array.prototype.subarray()
) instead of strings' native methods.However, for simple string manipulation tasks like this one, the built-in JavaScript methods are usually sufficient and efficient enough.