Additional string operation strategies
String pooling and lazy initialization are excellent optimization strategies that can help improve the overall performance of our Java applications. In addition to these strategies, we can ensure that our string concatenation operations are efficient, that we properly leverage regular expressions, and that we efficiently handle large text files. This section reviews techniques in each of those areas.
Concatenation
String concatenation – the joining of two or more strings into one – using the plus (+
) operator often results in inefficient code. This concatenation creates a new string object, which we want to avoid. Let’s look at two alternatives that offer better performance.
This first alternative uses StringBuilder
. In the following example, we create a StringBuilder
object, append five string literals to it, convert the StringBuilder
object to String
, and then output the results:
public class ConcatenationAlternativeOne...