|
String is the most probable variable used in Java programming, maybe you think there is nothing to say, just pick it up, but the processing of strings especially needs our attention, because the random creation of a large number of string instances brings great problems to the efficiency of the system. For example, let's do a test to compare the execution efficiency of the String class and StringBuffer: Our teacher said: Every time String is added, it will request space from memory again and again, which is very inefficient Every time StringBuffer is added, there is no need to request space from memory at once, because StringBuffer requests a lot of memory space from the beginning, so it is very efficient.
- import java.util.Date;
- public class test {
- /**
- * @param args
- */
- public static void main(String[] args) {
- // 武软论坛 www.itsvse.com
- Date da=new Date();
- System.out.println(da.toLocaleString());
- System.out.println("系统时间");
-
- String str1="1";
- for(int i=1;i<100000;i++){
- str1=str1+"1";
- }
- da=new Date();
- System.out.println(da.toLocaleString());
- System.out.println("String运行完时间");
-
- StringBuffer str2=new StringBuffer(1000);
-
- for(int i=1;i<100000;i++){
- str2.append("1");
- }
- da=new Date();
- System.out.println(da.toLocaleString());
- System.out.println("StringBuffer运行完时间");
-
- }
- }
Copy code
|