const segmenter = new Intl.Segmenter("ja", {granularity: "grapheme"});
โ
const str1 = "๐ ฎท้ๅฎถ";
const str2 = "๐๐ขโ";
const str3 = "๐จโข๐ฉโข๐งโข๐ฆ";
โ
var segments1 = segmenter.segment(str1);
var segments2 = segmenter.segment(str2);
var segments3 = segmenter.segment(str3);
const segments1Length = Array.from(segments1).length;
const segments2Length = Array.from(segments2).length;
const segments3Length = Array.from(segments3).length;
const segments1Length = [segments1].length;
const segments2Length = [segments2].length;
const segments3Length = [segments3].length;
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Array.from | |
Spread |
Test name | Executions per second |
---|---|
Array.from | 248150.9 Ops/sec |
Spread | 269386.2 Ops/sec |
Let's break down the provided benchmark and its test cases.
Benchmark Overview
The benchmark compares two approaches to get the length of an array created from an iterable: Array.from
and the spread operator (...
). The benchmark is designed to measure which approach is faster on average.
Script Preparation Code
The script preparation code uses the Intl.Segmenter
API to break down Japanese text into grapheme segments. This is likely done to ensure that the benchmark is representative of a real-world use case where arrays are created from iterables containing non-trivial data, such as strings with multiple characters.
Individual Test Cases
There are two test cases:
Array.from
to create an array from an iterable (in this case, the grapheme segments)....
) to create an array from an iterable.Library: Intl.Segmenter
The Intl.Segmenter
API is a built-in JavaScript library that splits text into smaller units called graphemes. Graphemes are the smallest units of text that can be meaningfully distinguished in a script, and they're often used for tasks like text processing, formatting, and language detection.
Test Results
According to the latest benchmark result, the spread operator (...
) is faster than Array.from
on this particular test case. This could be due to various factors, such as:
Intl.Segmenter
API are smaller and more lightweight than the individual characters returned by Array.from
, potentially leading to faster execution times.Pros and Cons
Here are some pros and cons of each approach:
Alternatives
If you're interested in exploring alternative approaches or testing different variants, consider these options:
Array.from()
with a custom iterator function to create an array from an iterable.map()
, filter()
, or reduce()
, to transform the iterable and get the desired output.These alternatives can provide valuable insights into the performance characteristics of various approaches, helping you make informed decisions about which method to use in your specific use case.