var example = 'there is no spoon'
var result = example.slice(-2)
var result = example.substr(-2)
var result = example.substring(-2)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
slice | |
substr | |
substring |
Test name | Executions per second |
---|---|
slice | 15403066.0 Ops/sec |
substr | 15281688.0 Ops/sec |
substring | 15372781.0 Ops/sec |
Let's break down what's being tested in the provided JSON.
The benchmark is comparing three string methods: slice()
, substr()
, and substring()
. These methods are used to extract a portion of a string, but they have slightly different behaviors depending on their parameters.
Here's a brief overview of each method:
slice(start, end)
: Extracts a section of the string from the specified start index up to but not including the end index.substr(start[, length])
: Extracts a portion of the string starting at the specified start index. The optional second argument specifies the number of characters to extract.substring(start, end)
: Similar to slice()
, extracts a section of the string from the specified start index up to but not including the end index.Now, let's discuss the options being compared:
slice()
, but it only extracts up to a specified end index, rather than including it.Pros and Cons:
undefined
as the length, it defaults to the string's length, which might not be what you expect. Also, if you pass a negative number for the length, it extracts from the end of the string instead of the beginning.Considerations:
slice()
is considered more flexible than substr()
because it allows specifying both indices and an optional length.substr()
might be more intuitive since you're less likely to expect an offset (length) being specified.Regarding the library or built-in functions used in this benchmark:
None of these methods rely on external libraries. They are all native JavaScript string methods that have been available since the language's early days.
If any special JavaScript features or syntax were mentioned, none are explicitly present here. However, some older versions of Internet Explorer had issues with slice()
and substr()
, including incorrectly handling negative lengths.
In summary, this benchmark helps compare how different browsers (specifically Chrome 96) handle the slicing and extraction of a string when only providing the start index or an offset in various methods, including slice()
, substr()
, and substring()
.