var example = 'AgreementChangeId'
var result = example.split(/(?=[A-Z])/).join(' ');
var result = example.replace(/([A-Z]+)/g, ' $1')
var result = example.split(/([A-Z])/).join(' ');
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
split + join | |
replace | |
Different regex split + join |
Test name | Executions per second |
---|---|
split + join | 1337765.1 Ops/sec |
replace | 801459.9 Ops/sec |
Different regex split + join | 1148689.1 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks.
What is being tested?
The benchmark tests three different approaches to achieve the same result: splitting and joining a string, replacing uppercase letters with spaces, and using a regular expression for splitting and joining.
Test case 1: Split + Join
split()
method with a regex pattern (?=[A-Z])
(positive lookahead) followed by the join(' ')
method to insert spaces between each split.Test case 2: Replace
replace()
method with a regex pattern [A-Z]+
(one or more uppercase letters) followed by a replacement string $1
to insert a space before each matched uppercase letter.replace()
method for large strings.Test case 3: Different Regex Split + Join
split()
method with a regex pattern ([A-Z])
(capture group) followed by the join(' ')
method to insert spaces between each split.replace()
method.Other considerations
Alternatives
If you're looking for alternative approaches, consider the following:
replace()
method with an array of replacement strings (e.g., example.replace(/([A-Z]+)/g, ' $1')
)These alternatives might offer better performance or ease of use in specific scenarios. However, for most cases, the original approaches tested on MeasureThat.net should suffice.