var dateStr = "2021-08-10T06:00:00.000Z"
[yyyy,mm,dd,hh,mi] = dateStr.split(/[/:\-T]/)
const result =`${dd}/${mm}/${yyyy}, ${hh}:${mi}`
const result = new Date(dateStr).toLocaleString("en-GB")
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
split | |
Date toLocaleString |
Test name | Executions per second |
---|---|
split | 486875.7 Ops/sec |
Date toLocaleString | 237853.8 Ops/sec |
Overview
MeasureThat.net is a website that allows users to create and run JavaScript microbenchmarks to compare the performance of different approaches. In this case, we're analyzing a benchmark that tests two ways of formatting dates: using string.split()
versus using toLocaleString()
. We'll break down what's tested, compared, pros and cons of each approach, and discuss libraries and special JS features used.
Benchmark Definition
The benchmark definition is a JSON object that contains information about the test case:
{
"Name": "string.split vs toLocaleString(\"en-GB\")",
"Description": null,
"Script Preparation Code": "var dateStr = \"2021-08-10T06:00:00.000Z\"",
"Html Preparation Code": null
}
The Script Preparation Code
specifies a sample date string (dateStr
) that will be used for the test.
Test Cases
There are two individual test cases:
[
{
"Benchmark Definition": "[yyyy,mm,dd,hh,mi] = dateStr.split(/[/:\\-T]/)\r\nconst result =`${dd}/${mm}/${yyyy}, ${hh}:${mi}`",
"Test Name": "split"
},
{
"Benchmark Definition": "const result = new Date(dateStr).toLocaleString(\"en-GB\")",
"Test Name": "Date toLocaleString"
}
]
Each test case has a Benchmark Definition
that describes how the date will be formatted and what the resulting code looks like.
What's being tested
In each test case, we're testing the performance of two different approaches:
string.split()
: The first test case uses split()
to extract the individual components (year, month, day, hour, minute) from the date string and then concatenates them into a new string using template literals.Date.toLocaleString()
: The second test case uses the Date
constructor to parse the date string and then calls toLocaleString()
with a locale (en-GB
) to format the date.Comparison of approaches
Here's a brief comparison of the two approaches:
string.split()
:Date.toLocaleString()
:Library used
In this benchmark, the toLocaleString()
method uses the Date
API, which is a built-in JavaScript library. This means that no external libraries are required to run the test.
Special JS feature
There's no special JS feature being used in this benchmark beyond the standard features of the languages (JavaScript).
Alternative approaches
Other ways to format dates in JavaScript might include:
dateparser
APIKeep in mind that each of these alternatives has its own trade-offs in terms of performance, reliability, and complexity.
I hope this explanation helps!