String Builders and Smart Compilers - DZone Java
For a long time, this has been seen as a bad practice, because of the nature of strings in the Java programming language. In Java, every string is immutable; if it needs to change, a new string object is created, and the contents are copied over.
For the most part, this is done to allow Java to avoid a large class of buffer overflows that occur from reading off the end of a string. It's the same reason that the size of an array is established at the time of its instantiation.
So we look at this code and imagine that for each plus sign, a new string object is created, which of course would be wildly inefficient. Of course, most Java developers also know that the Java compiler is smarter than that. Instead of creating a string object for each concatenation, or a single new string object for all the concatenations, it uses the StringBuilder class that is built into the Java standard library.
Read full article from String Builders and Smart Compilers - DZone Java
No comments:
Post a Comment