Reputation: 5819
I am replacing a string using RegEx. I knew that the pattern which I search in that string may occur only once. Both replaceAll()
and replaceFirst()
methods will work for my scenario. But I am using replaceAll()
method.
In my application every millisecond on computation is precious.
Is my choice right? Which one is better for my scenario? Any comparisons available? Please guide me.
Upvotes: 0
Views: 465
Reputation: 354456
If every millisecond is precious for you then you should measure not ask. In any case, my guess (again: verify by measuring) is that replaceFirst()
will be faster since it can stop after the first match instead of searching for others (that won't exist in your case).
You probably also want to precompile the regex as that saves you the time to do so on every call to replaceFirst()
. Or look for a way of avoiding regular expressions if it's just a simple string replace.
But I stress again: Use a profiler to find out where you spend the most time and optimise that part. It's not very useful to over-optimise a statement that is called exactly once and contributes just 0.07 % to the total runtime while ignoring the fat loop right next to it, eating up 80 % of your runtime. Also so far my experience has been that the bottlenecks are very often in the most surprising places and not where you'd naïvely expect them.
Upvotes: 18
Reputation: 37566
Surely replaceFirst()
is faster, it will stop after the first occurence while replaceAll()
will scan the entire input.
Upvotes: 1