Strings

来源:互联网 发布:什么软件有淘宝优惠卷 编辑:程序博客网 时间:2024/05/16 08:44
Overloading '+' vs. StringBuilder
SinceString objects are immutable, you can alias to a particular String as many times as you want. Because a String is read-only, there’s no possibility that one reference will change something that will affect the other references. Immutability can have efficiency issues. A case in point is the operator '+' that has been overloaded for String objects. Overloading means that an operation has been given an extra meaning when used with a particular class. (The '+' and '+=' for String are the only operators that are overloaded in Java, and Java does not allow the programmer to overload any others.) The '+' operator allows you to concatenate Strings
public class Concatenation {    public static void main(String[] args) {        String mango = "mango";        String s = "abc" + mango + "def" + 47;        System.out.println(s);    }}
You could imagine how this might work. TheString "abc" could have a methodappend( ) that creates a new String object containing "abc" concatenated with the contents of mango. The newString object would then create another newString that added "def" and so on.  
This would certainly work, but it requires the creation of a lot ofString objects just to put together this new String, and then you have a bunch of intermediateString objects that need to be garbage collected. I suspect that the Java designers tried this approach first (which is a lesson in software design—you don’t really know anything about a system until you try it out in code and get something working). I also suspect that they discovered it delivered unacceptable performance. To see what really happens, you can decompile the above code using thejavap tool that comes as part of the JDK. Here’s the command line: 
javap -c Concatenation