var testString = "testing\nNewlines\nBleh"
var values = testString.split("\n");
var value1 = values[0];
var value2 = values[1];
var value3 = values[2];
var regex = testString.match(/.+((?=\n)|$)/g)
var value1 = regex[0];
var value2 = regex[1];
var value3 = regex[2];
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Splitting | |
Regex |
Test name | Executions per second |
---|---|
Splitting | 9880450.0 Ops/sec |
Regex | 8812837.0 Ops/sec |
Let's dive into the benchmark and explain what's being tested.
Benchmark Overview
The benchmark is designed to compare two approaches: splitting a string using split()
and using regular expressions (regex
).
Split() vs Regex
The test case uses a string testString
containing multiple newlines (\n
). The goal is to split this string into individual lines and extract the first three values.
Split() Approach
var values = testString.split("\n");
var value1 = values[0];
var value2 = values[1];
var value3 = values[2];
Pros:
Cons:
Regex Approach
var regex = testString.match(/.+((?=\\n)|$)/g);
var value1 = regex[0];
var value2 = regex[1];
var value3 = regex[2];
Pros:
Cons:
Library: String.prototype.split()
The split()
method is a built-in JavaScript method that splits an array-like object (including strings) into an array of substrings. This library is included in most browsers and Node.js environments.
Special JS Feature/Syntax
There are no special features or syntaxes being tested in this benchmark.
Other Alternatives
For splitting strings, other approaches include:
String.prototype.split()
with a custom separator (e.g., testString.split("|")
)lodash.string
for string manipulationArray.prototype.map()
or Array.prototype.filter()
For regex, other approaches include:
String.prototype.match()
with a custom pattern (e.g., /[^\\n]+/g
)lodash.regex
for regular expression manipulationArray.prototype.map()
or Array.prototype.filter()
Overall, the benchmark provides a simple and clear comparison between two approaches to splitting strings in JavaScript.