var strTxt = Array(100000).fill("@".repeat(128)).join(" "), len = 2;
var ar = strTxt.matchAll(new RegExp('.{1,'+len+'}','g'));
console.log(ar.next().value[0]);
var ar = [];
for(i=0,y=0;i<Math.ceil(strTxt.length/len);i++,y=i*len){
ar[i] = strTxt.slice(y,y+len);
}
console.log(ar[0]);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
testttttt | |
tesstttt2 |
Test name | Executions per second |
---|---|
testttttt | 66129.2 Ops/sec |
tesstttt2 | 0.1 Ops/sec |
Benchmark Overview
MeasureThat.net is a website that allows users to create and run JavaScript microbenchmarks. The provided benchmark definition and test cases represent two different approaches to measure the performance of splitting a large string into substrings.
Benchmark Definition
The benchmark definition consists of two parts:
strTxt
with a large string containing 100,000 repetitions of a specific character (@
). The length of each repetition is determined by another variable len
, which is set to 2.Individual Test Cases
There are two test cases:
matchAll
var ar = strTxt.matchAll(new RegExp('.{1,'+len+'}','g'));
console.log(ar.next().value[0]);
This code uses the matchAll
method of the String
prototype to split the large string into an array of matches. The regular expression used is . {1,}
+ len
, which matches any character (including newline) between 1 and len
times. The g
flag at the end of the regular expression makes it match all occurrences in the string.
var ar = [];
for(i=0,y=0;i<Math.ceil(strTxt.length/len);i++,y=i*len){
ar[i] = strTxt.slice(y,y+len);
}
console.log(ar[0]);
This code uses a manual loop to split the large string into an array of substrings. The loop iterates over the length of the string, and for each iteration, it extracts a substring of length len
starting from the current index y
.
Comparison of Approaches
The two approaches have different pros and cons:
matchAll
: This approach is more concise and efficient, as it uses the optimized regular expression engine to split the string. However, it may not be as fast for very large strings or if the regular expression pattern is complex.Library and Special JS Features
There are no libraries explicitly mentioned in the benchmark definition. However, JavaScript's built-in String
prototype methods, such as matchAll
, are used.
No special JavaScript features or syntax are used in these test cases.
Alternatives
Other alternatives to measure the performance of splitting a large string include:
split()
or substring()
.Map
or Promise.all()
, to split the string concurrently.Note that MeasureThat.net's benchmarking framework allows users to explore these alternatives and compare their performance with the two approaches provided in the test cases.