Abid
Abid

Reputation: 91

String replacement efficiency java

Which way is more efficient to replace characters/substring in a string. I have searched and i have found two ways :

output = output.replaceAll(REGEX, REPLACEMENT);

or

Pattern p = Pattern.compile(REGEX);
Matcher m = p.matcher(output);
output = m.replaceAll(REPLACEMENT);

I mean with efficiency : less time, loops and/or new variables.

Upvotes: 0

Views: 62

Answers (1)

Justas
Justas

Reputation: 811

If you look at the String method replaceAll it does the same under the hood:

public String replaceAll(String regex, String replacement) {
    return Pattern.compile(regex).matcher(this).replaceAll(replacement);
}

If you want to use the same pattern multiple times. It's better to go with the second option as you will not need to recompile it every time.

Upvotes: 4

Related Questions