var str = 'foo.bar'
const [foo] = str.split('.')
const foo = str.substring(0, str.indexOf("."))
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
String.split | |
String.substring |
Test name | Executions per second |
---|---|
String.split | 512958.8 Ops/sec |
String.substring | 638281.6 Ops/sec |
Let's break down the benchmark and explain what's being tested.
Benchmark Definition
The benchmark is defined by a JSON object that describes two test cases:
String.split vs String.substring
String.split
with the benchmark definition: const [foo] = str.split('.')
String.substring
with the benchmark definition: const foo = str.substring(0, str.indexOf(\".\"))
What is being tested?
The benchmark is testing two different approaches to splitting a string in JavaScript:
String.split()
: This method splits a string into an array of substrings using a specified separator.String.substring()
: This method extracts a substring from a given string, starting at a specified position and ending at another specified position.Options compared
The benchmark is comparing the performance of these two approaches:
String.split()
with and without specifying a separatorString.substring()
with and without using indexOf()
to determine the end positionPros and cons of each approach
String.split()
String.substring()
String.split()
for small strings or when using a default separator.Library usage
The benchmark does not use any specific libraries. However, if the String
prototype were used, it would be a built-in library.
Special JS feature or syntax
There is no special JavaScript feature or syntax being tested in this benchmark. The focus is on comparing the performance of two basic string manipulation methods.
Other alternatives
If you wanted to compare other approaches for splitting strings, here are some alternatives:
String.prototype.split()
with a default separator (e.g., const [foo] = str.split('');
)const match = str.match(/\./g); const foo = match[0];
)indexOf()
and indexing into the stringKeep in mind that these alternatives may have different performance characteristics, trade-offs, and use cases compared to the original benchmark.