This article is a mirror article of machine translation, please click here to jump to the original article.

View: 16249|Reply: 0

[Tips] Essential for Java to run efficiently: StringBuffer is more efficient than String

[Copy link]
Posted on 11/6/2014 10:58:08 AM | | | |

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.



  1. import java.util.Date;






  2. public class test {

  3.         /**
  4.          * @param args
  5.          */
  6.         public static void main(String[] args) {
  7.                 // 武软论坛 www.itsvse.com
  8.                 Date da=new Date();
  9.                 System.out.println(da.toLocaleString());
  10.                 System.out.println("系统时间");
  11.                
  12.                 String str1="1";
  13.                 for(int i=1;i<100000;i++){
  14.                         str1=str1+"1";
  15.                 }
  16.                 da=new Date();
  17.                 System.out.println(da.toLocaleString());
  18.                 System.out.println("String运行完时间");
  19.                
  20.                 StringBuffer str2=new StringBuffer(1000);
  21.                
  22.                 for(int i=1;i<100000;i++){
  23.                         str2.append("1");
  24.                 }
  25.                 da=new Date();
  26.                 System.out.println(da.toLocaleString());
  27.                 System.out.println("StringBuffer运行完时间");
  28.                
  29.         }

  30. }
Copy code






Previous:2007 Office System Compatibility Pack Download
Next:Talking about software compatibility testing
Disclaimer:
All software, programming materials or articles published by Code Farmer Network are only for learning and research purposes; The above content shall not be used for commercial or illegal purposes, otherwise, users shall bear all consequences. The information on this site comes from the Internet, and copyright disputes have nothing to do with this site. You must completely delete the above content from your computer within 24 hours of downloading. If you like the program, please support genuine software, purchase registration, and get better genuine services. If there is any infringement, please contact us by email.

Mail To:help@itsvse.com