关于少量字符串拼接的选择

/**

  • @Author ChenQ
  • System.gc的使用场景
  •  用于调用垃圾收集器,在调用时,垃圾收集器将运行以回收未使用的内存空间。
    
  •  它将尝试释放被丢弃对象占用的内存。然而System.gc()调用附带一个免责声明,
    
  •  无法保证对垃圾收集器的调用。我们习惯了从现实世界的经验中获得的“条件适用”。一切都附有免责声明!
    
  •  JVM实现者可以通过System.gc()调用来决定JVM的行为。一般来说,我们在编写Java代码并将其留给JVM时,
    
  •  不要考虑内存管理。在一些特殊情况下,如我们正在编写一个性能基准,我们可以在运行之间调用System.gc()。
    
  •  以下是调用gc有所作为的另一个例子。
    

*/

  public class StringTest{
      public static void main(String[] args) {

        String str1 = "yveshe";
        String str2 = "hello";
      
        /**
         * <P>concat</P>
         */
        System.gc();
        long startTime1 = System.currentTimeMillis();
        for (int i = 0; i < 10000; i++) {
            str1 = str1.concat(str2);
        }
        long endTime1 = System.currentTimeMillis();
        System.out.println("concat:" + (endTime1 - startTime1)+"毫秒值");

        /**
         * <P>+</P>
         */
        str1 = "yveshe";
        System.gc();
        long startTime2 = System.currentTimeMillis();
        for (int i = 0; i < 10000; i++) {
            str1 = str1 + str2;
        }
        long endTime2 = System.currentTimeMillis();
        System.out.println("+: " + (endTime2 - startTime2)+"毫秒值");
    }
}
  • 运行结果

concat: 182毫秒值 +: 381毫秒值

原文地址:https://www.cnblogs.com/ChenQ2/p/15330608.html