Home » Java » java – String versus StringBuilder-Exceptionshub

java – String versus StringBuilder-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:

I need to modify the input string to return some output. Basically, when I see a particular string I need to remove it. I am thinking whether to use StringBuilder versus String. From my perspective, String would be much simpler.

Suppose:

StringBuilder input = new StringBuilder(inputs)
if(inputs.contains("someword)"")) {
     // remove it by inputs = inputs.replace("someword", "");
}

Is it better to use StringBuilder input = new StringBuilder(inputs) and delete the particular string or use the original inputs = inputs.replace(...).

I think it will get messy to use StringBuilder. StringBuilder is used for concatentation, but I am not concentating strings.

How to&Answers:

In the past, StringBuilder was most times much faster than String when you applied multiple modifications to a String.

But since JDK 6, the compiler itself replaces String often automatically by StringBuilder (including all related lines) when this may improve the performance. This becomes visible by the use of a decompiler. So in most cases you won’t notice any difference.

If you apply multiple operations to a string in a more complex structure than a simple batch of commands, then using StringBuilder is still better than the automatic compiler optimization.