var testString = new Array(1000).fill(0).map(() => Math.random().toFixed(4)).join("\n");
testString.split("\n").forEach(v => {
const f = parseFloat(v);
if (!window.screen) console.log(f);
});
var regex = /([^\n]+)\n/g
while (true) {
const match = regex.exec(testString);
if (!match) break;
const f = parseFloat(match[1]);
if (!window.screen) console.log(f);
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Splitting | |
Regex |
Test name | Executions per second |
---|---|
Splitting | 4362.2 Ops/sec |
Regex | 3232.0 Ops/sec |
Let's break down the provided benchmark and explain what's being tested.
Benchmark Overview
The benchmark, titled "Split vs Regex Iteration", compares two approaches to parse a string: splitting and regular expressions (Regex). The test aims to determine which approach is faster on different browsers and devices.
Script Preparation Code
The script preparation code generates a large string testString
consisting of 1000 random numbers, each with four decimal places, separated by newline characters (\n
). This creates a significant number of iterations for the benchmark.
Individual Test Cases
There are two test cases:
split()
method to split the string into an array of substrings, using \n
as the separator. Each substring is then processed to extract a floating-point number (f
) and log it to the console if the user doesn't have a screen ( likely referring to a headless browser environment)./([^\\n]+)\\n/g
which matches any sequence of characters ([^\\n]+
) followed by \n
. The exec()
method is used to execute this pattern on each substring, extracting the matched value and logging it to the console.Library/Functionality Used
Neither script explicitly uses a library, but both rely on built-in JavaScript functionality:
split()
: A standard array method in JavaScript.RegExp
): Another standard JavaScript function for working with patterns.Special JS Feature/Syntax
Both test cases do not use any special or experimental JavaScript features.
Options Compared
The two options being compared are:
split()
method to split the string into an array of substrings.Pros and Cons
Here's a brief overview of each approach:
Other Considerations
When interpreting benchmark results, consider factors like:
Alternatives
Some alternative approaches could include:
string-parsing
or parse-string
that provide optimized functions for handling strings.String.prototype.replace()
) might be more efficient.However, these alternatives are not explicitly mentioned in the benchmark and may not be relevant to this specific comparison between splitting and regular expressions.