Java字符串连接效率

字符串操作是编写程序中最常见的行为,香港空间,本文对String、StringBuilder、StringBuffer三个类在字符串处理方面的效率进行分析。

Java中最常见也是应用最广泛的类就是String类。

String:Strings are constant; their values cannot be changed after they are created.

这是JDK对String的解释,意思是:String是常量,一旦创建后它的值不能被修改。

先看String对象是如何创建的:

String str1 = “abc”;

String str2 = new String(“abc”);

这是我们常见的两种形式。

第一种方式创建的字符串会放在栈里,香港虚拟主机,更确切的是常量池中,常量池就是用来保存在编译阶段确定好了大小的数据,一般我们定义的int等基本数据类型就保存在这里。其具体的一个流程就是,编译器首先检查常量池,看看有没有一个“abc”,如果没有则创建。如果有的话,则则直接把str1指向那个位置。

第二种创建字符串的方法是通过new关键字,还是java的内存分配,java会将new的对象放在堆中,美国空间,这一部分对象是在运行时创建的对象。所以我们每一次new的时候,都会创建不同的对象,即便是堆中已经有了一个一模一样的。

下面的程序将验证上面的说法。

1 String str1 = “abc”; 2 String str2 = new String(“abc”); 3 4 String str3 = “abc”; 5 String str4 = new String(“abc”); 6 7 System.out.println(str1==str2);//false 89 System.out.println(str1 == str3);//true10 System.out.println(str2 == str4);//false11 // When the intern method is invoked, if the pool already contains a12 // string equal to this String object as determined by the13 // equals(Object) method, then the string from the pool is returned.14 // Otherwise, this String object is added to the pool and a reference to15 // this String object is returned.16 str2 = str2.intern();17 System.out.println(str1==str2);//true18 19 false20 true21 false22 true让你的心情地落到极点,一直学习生活等各个方面都做不好,最终害的还是自己。

Java字符串连接效率

相关文章:

你感兴趣的文章:

标签云: