Search code examples
javastringperformancestringbuilder

Java String.replace() or StringBuilder.replace()


In scenarios where I am using 5-10 replacements is it necessary to use stringbuilder.

String someData = "......";
someData = someData.replaceAll("(?s)<tag_one>.*?</tag_one>", "");
someData = someData.replaceAll("(?s)<tag_two>.*?</tag_two>", "");
someData = someData.replaceAll("(?s)<tag_three>.*?</tag_three>", "");
someData = someData.replaceAll("(?s)<tag_four>.*?</tag_four>", "");
someData = someData.replaceAll("(?s)<tag_five>.*?</tag_five>", "");
someData = someData.replaceAll("<tag_five/>", "");
someData = someData.replaceAll("\\s+", "");

Will it make a difference if I use stringBuilder Here.


Solution

  • Using StringBuilder won't make a useful difference here.

    A better improvement would be to use a single regex:

    someData = someData.replaceAll("(?s)<tag_(one|two|three|four|five)>.*?</tag_\\1>", "");
    

    Here, the \\1 matches the same thing that was captured in the (one|two|etc) group.