zoukankan      html  css  js  c++  java
  • StringBuilder、StringBuffer、String类之间的关系

    【详情点击链接: http://www.test-life.org/?p=56 | 测试之路-My Test Space

    public class TestCharacter {
    final static int time = 50000;  //循环次数

    public TestCharacter(){

    }
    public void test(String s){
    long begin = System.currentTimeMillis();
    for(int i=0; i<time; i++){
    s += “add”;
    }
    long over = System.currentTimeMillis();
    System.out.println(“操作”+s.getClass().getName()+”类型使用的时间为:”+(over-begin)+”毫秒”);
    }
    public void test(StringBuffer s){
    long begin = System.currentTimeMillis();
    for(int i=0; i<time; i++){
    s.append(“add”);
    }
    long over = System.currentTimeMillis();
    System.out.println(“操作”+s.getClass().getCanonicalName()+”类型使用的时间为:”+(over-begin)+”毫秒”);
    }
    public void test(StringBuilder s){
    long begin = System.currentTimeMillis();
    for(int i=0; i<time; i++){
    s.append(“add”);
    }
    long over = System.currentTimeMillis();
    System.out.println(“操作”+s.getClass().getName()+”类型使用的时间为:”+(over-begin)+”毫秒”);
    }

    /*对 String 直接进行字符串拼接的测试*/
    public void test2(){
    String s2 = “abcd”;
    long begin = System.currentTimeMillis();
    for(int i=0; i<time; i++){
    String s = s2 + s2 +s2;
    }
    long over = System.currentTimeMillis();
    System.out.println(“操作字符串对象引用相加类型使用的时间为:”+(over-begin)+”毫秒”);
    }
    public void test3(){
    long begin = System.currentTimeMillis();
    for(int i=0; i<time; i++){
    String s =”abcd” + “abcd” + “abcd”;
    }
    long over = System.currentTimeMillis();
    System.out.println(“操作字符串相加使用的时间为:”+(over-begin)+”毫秒”);
    }
    public static void main(String[] args){
    String s1 = “abcd”;
    StringBuffer st1 = new StringBuffer(“abcd”);
    StringBuilder st2 = new StringBuilder(“abcd”);
    TestCharacter tc = new TestCharacter();
    tc.test(s1);
    tc.test(st1);
    tc.test(st2);
    tc.test2();
    tc.test3();
    }
    }
    我在myeclipse和dos下都运行了这段代码,各自打印出的时间有些不同,运行结果如下:
    1)myeclipse下循环10000次时:

    2)myeclipse下循环50000次时:

    3)在DOS下运行时:

    本文固定链接: http://www.test-life.org/?p=56 | 测试之路-My Test Space

  • 相关阅读:
    【简单算法】27.验证二叉搜索树
    【简单算法】26. 二叉树的最大深度
    【简单算法】25. 环形链表
    pandas 数据处理
    主成分分析 PCA
    hive 导出数据到本地
    深度学习的优化方法 总结
    ALS算法 (面试准备)
    Bagging和Boosting的区别(面试准备)
    ROC 曲线,以及AUC计算方式
  • 原文地址:https://www.cnblogs.com/seiitsu/p/2869162.html
Copyright © 2011-2022 走看看