var dates = [
"01-12-2019",
"11-11-2064",
"07-03-2032",
"08-08-2002",
"08-01-2001",
"22-12-2018",
"28-02-2022",
];
for(let i=0; i<dates.length; i++) {
let date = dates[i].split("-");
let dateString = date[2]+"-"+date[1]+"-"+date[0];
}
for(let i=0; i<dates.length; i++) {
let dateString = dates[i].substr(6,4)+"-"+dates[i].substr(4,2)+"-"+dates[i].substr(0,2);
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Split | |
Substring |
Test name | Executions per second |
---|---|
Split | 403136.7 Ops/sec |
Substring | 292600.4 Ops/sec |
Let's break down the provided benchmarking setup and explain what's being tested, compared, and the pros and cons of each approach.
Benchmark Overview
The benchmark measures the performance difference between two approaches: split()
and substr()
when extracting date components from a string.
Script Preparation Code
The script preparation code defines an array of dates in the format "dd-mm-yyyy". This is used as input for the benchmarking test cases.
Individual Test Cases
There are two test cases:
for(let i=0; i<dates.length; i++) {
let date = dates[i].split("-"); // split on "-" delimiter
let dateString = date[2] + "-" + date[1] + "-" + date[0]; // assemble date string
}
This test case uses the split()
method to split the date string into an array of substrings, and then uses indexing (date[2]
, date[1]
, and date[0]
) to extract the individual date components.
for(let i=0; i<dates.length; i++) {
let dateString = dates[i].substr(6,4) + "-" + dates[i].substr(4,2) + "-" + dates[i].substr(0,2); // extract date components using substr()
}
This test case uses the substr()
method to extract specific parts of the date string. The syntax is as follows:
dates[i].substr(startIndex, length)
extracts a substring starting at startIndex
with a length of length
.Comparison
The benchmark compares the performance of the two approaches: split()
and substr()
. The test case with the highest execution rate (in this case, "Split") is considered faster.
Pros and Cons
Library/Language Features
There is no explicit library or language feature being used in this benchmark. However, it's worth noting that the split()
method is a built-in JavaScript method that splits a string into an array of substrings based on a specified delimiter.
Special JS Feature/Syntax
There are no special JavaScript features or syntax being tested in this benchmark. The focus is solely on comparing two basic string manipulation approaches: split()
and substr()
.