Find your content:

Search form

You are here

Regex replacement efficiency

 
Share

In a recent question (Remove whitespaces in a string) my solution included using a simple regex replacement (\\s+) to match all instances of double spaces (or more) and reduce them to a single space.

While this works great its been bugging me that the code might not be a little more efficient to use (\\s\\s+) as this would reduce the number of matches requiring replacement.

Short Question

Is it more efficient to use a more complex regex match when doing a replaceAll()


Attribution to: Jon Hazan

Possible Suggestion/Solution #1

It can depend upon the regex engine used which optimisation will perform best. Given Apex's closeness to java the following article might be of interest to you - http://www.javaworld.com/javaworld/jw-09-2007/jw-09-optimizingregex.html.

However given the simple nature of the regex in question I'd always go with the one which is easier for a future developer (or you) to read and interpret correctly.


Attribution to: David Gillen

Possible Suggestion/Solution #2

Performance of various patterns will depend on the regex engine involved, but it would seem to me that the less generic your pattern (i.e. the more concise it is) then the faster it will fail against strings that don't match the full pattern. The faster tests fail against 'bad' strings then the greater the overall performance.

All that aside, in this scenario (as with many other scenarios when working on the platform), such optimisations are likely to be irrelevant (unless we're talking about a batch process operating on millions of records!). Unless the code in question causes a pause you can perceieve, chances are the time taken to execute it is going to be negligible when compared with the time taken for data transfer back to the user.


Attribution to: Matt Lacey
This content is remixed from stackoverflow or stackexchange. Please visit https://salesforce.stackexchange.com/questions/1752

My Block Status

My Block Content