Toggle navigation
MeasureThat.net
Create a benchmark
Tools
Feedback
FAQ
Register
Log In
String.replace using regex vs string
(version: 1)
Comparing performance of:
Replace with regex vs Replace with string
Created:
one year ago
by:
Guest
Jump to the latest result
HTML Preparation code:
<!--your preparation HTML code goes here-->
Script Preparation code:
let str = "To be, or not to be: that is the question: whether 'tis nobler in the mind to suffer the slings and arrows of outrageous fortune, or to take arms against a sea of troubles, and by opposing end them? To die: to sleep; no more; and, by a sleep to say we end the heart-ache and the thousand natural shocks that flesh is heir to, 'tis a consummation devoutly to be wish'd. To die, to sleep; to sleep: perchance to dream: ay, there's the rub; for in that sleep of death what dreams may come when we have shuffled off this mortal coil, must give us pause. There's the respect that makes calamity of so long a life; for who would bear the whips and scorns of time, the oppressor's wrong, the proud man's contumely, the pangs of dispriz'd love, the law's delay, the insolence of office, and the spurns that patient merit of the unworthy takes, when he himself might his quietus make with a bare bodkin? Who would fardels bear, to grunt and sweat under a weary life, but that the dread of something after death, the undiscover'd country from whose bourn no traveller returns, puzzles the will, and makes us rather bear those ills we have, than fly to others that we know not of? Thus consience doth make cowards of us all; and thus the native hue of resolution is sicklied o'er with the pale cast of thought, and enterprises of great pith and moment with this regard their currents turn awry, and lose the name of action."; let regex = /traveller/;
Tests:
Replace with regex
let res = str.replace(regex, "explorer");
Replace with string
let res = str.replace("traveller", "explorer");
Rendered benchmark preparation results:
Suite status:
<idle, ready to run>
Run tests (2)
Previous results
Fork
Test case name
Result
Replace with regex
Replace with string
Fastest:
N/A
Slowest:
N/A
Latest run results:
Run details:
(Test run date:
one year ago
)
User agent:
Mozilla/5.0 (Android 14; Mobile; rv:139.0) Gecko/139.0 Firefox/139.0
Browser/OS:
Firefox Mobile 139 on Android
View result in a separate tab
Embed
Embed Benchmark Result
Test name
Executions per second
Replace with regex
1253521.5 Ops/sec
Replace with string
1264244.5 Ops/sec
Autogenerated LLM Summary
(model
gpt-4o-mini
, generated one year ago):
### Benchmark Overview The benchmark tests the performance of two different methods of replacing substrings in a large string using JavaScript. The methods being compared are: 1. **Replacing with a Regex** - **Test Name**: Replace with regex - **Benchmark Definition**: `let res = str.replace(regex, "explorer");` 2. **Replacing with a Direct String Match** - **Test Name**: Replace with string - **Benchmark Definition**: `let res = str.replace("traveller", "explorer");` ### Comparison of Approaches #### 1. Replacing with Regex - **Pros**: - Ability to perform complex matches (e.g., case-insensitivity, pattern matching). - Can be used to find patterns rather than just exact string matches. - **Cons**: - Generally slower for simple string replacements due to the overhead associated with interpreting the regex pattern. - May not be necessary for straightforward substring replacements, which can lead to less efficient code if overused. #### 2. Replacing with String - **Pros**: - Typically faster since it does not involve the additional overhead of regex parsing. - More straightforward and readable when the exact substring is known, making it suitable for simple replacements. - **Cons**: - Limited to exact matches, meaning it won’t work for patterns (e.g., "cat" won't match "Cats"). - Less flexible than regex for cases where more complex rules are needed for replacements. ### Benchmark Results The latest benchmark results provide us with performance data for each approach when executed in Firefox (version 135) on Windows: - **Replace with string**: **10,748,226** executions per second. - **Replace with regex**: **10,225,132** executions per second. The results indicate that replacing with a straightforward string match is approximately 5% faster compared to using regex, which aligns with expectations given the simplicity and efficiency of direct string replacements. ### Libraries and Other Considerations For this specific benchmark, no external libraries were used, as both operations rely solely on the built-in `String.replace()` method provided by JavaScript. ### Alternatives 1. **Using String.prototype.split() and Array.join()**: - One potential alternative to replace strings involves breaking the original string into an array and then joining it back together with the new substring. This may offer differences in performance based on the context, but it can add complexity and potentially impact readability. 2. **Manual String Replacement**: - For very specific tasks or where performance is critical, implementing a manual search and replace algorithm might provide speed improvements, especially in cases where many replacements are clustered together. 3. **More Efficient Libraries**: - For more complex scenarios, libraries such as `lodash` or `underscore.js` provide various utility functions that can facilitate string and array manipulations, but they are likely unnecessary if simple replacements are required. In conclusion, while regex and direct string replacement are both valid approaches for modifying strings in JavaScript, understanding their strengths and weaknesses in different contexts can lead to more effective and efficient code. This benchmark sheds light on practical performance differences, helping developers make informed choices based on the specific needs of their applications.
Related benchmarks:
Array split vs string substring big text
replaceAll vs regex replace v2
Regex match() array vs matchAll() iterator
deep clone - lodash vs ramda vs structuredClone
RegEx.test vs. String.includes vs. String.match (long)
regex replace vs split vs loop
Array from vs string split with large strings
String.replace(RegEx) vs String.replaceAll(String)
replaceAll no regex vs replace with regex
Comments
Confirm delete:
Do you really want to delete benchmark?