3

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()

  • 2
    Specifically to your example I get a 4ms average for replacing spaces in 100 strings for both regular expressions. Average calculated over 100 executions. – Samuel De Rycke Sep 28 '12 at 12:30
  • Since the average SOQL query takes at least 10000x the resources of a regex execution, I wouldn't really worry about optimizing regexes unless you have a very specific problem with inefficiency or overflows. – jkraybill Oct 1 '12 at 7:15
  • @jkraybill I realise in the scope of a whole application this is a minor efficiency change (if at all based on Sdry's test). But its a question that kept bouncing round my head! – Jon Hazan Oct 1 '12 at 9:25
7

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.

| improve this answer | |
6

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.

| improve this answer | |
  • 1
    Good point on optimizing before profiling (as it pertains to cloud computing.) – Mike Chale Sep 28 '12 at 14:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.