zoukankan      html  css  js  c++  java
  • 字符串 —— String?StringBuffer?StringBuilder?

    字符串常用的操作就是拼接,特别是SQL语句的拼接。

    做了个简单的试验,它们之间的差别惊人!

    StringBuffer:

     1     public void testStringBuffer() {
     2         long start = System.currentTimeMillis();
     3         StringBuffer sb = new StringBuffer();
     4         
     5         for (int i = 0; i < COUNT; i++) {
     6             sb.append(STR_INIT);
     7         }
     8         long end = System.currentTimeMillis();
     9         
    10         System.out.println("StringBuffer 耗时:"  + (end - start));
    11     }

    运行结果:基本在50毫秒

    StringBuilder:

     1     public void testStringBuilder() {
     2         long start = System.currentTimeMillis();
     3         StringBuilder sb = new StringBuilder();
     4         
     5         for (int i = 0; i < COUNT; i++) {
     6             sb.append(STR_INIT);
     7         }
     8         long end = System.currentTimeMillis();
     9         
    10         System.out.println("StringBuilder 耗时:"  + (end - start));
    11     }

    运行结果:平均50毫秒,最低30多毫秒,最高90多毫秒

    String:

     1     public void testString() {
     2         long start = System.currentTimeMillis();
     3         String s = "";
     4         
     5         for (int i = 0; i < COUNT; i ++) {
     6             s += STR_INIT;
     7         }
     8         
     9         long end = System.currentTimeMillis();
    10         
    11         System.out.println("Str 耗时:"  + (end - start));
    12     }

    运行结果:2分多钟(是StringBuffer,StringBilder的上千倍

    代码说明:

    for循环的次数(COUNT)为 10000


    StringBuffer和StringBuilder的区别:

    StringBuffer——线程安全的

    StringBuilder——非线程安全

    JDK API建议:如果不涉及线程问题,建议使用StringBuilder

    个人建议:当需要字符串做拼接时,使用StringBuilder吧!


    UPDATE:2016-5-23

    重新学习发现内存也是可以计算的。

    内存的差别倒是不大,跟时间比起来,可以忽略不计了。

    详细代码请参考:Github

  • 相关阅读:
    python selenium启动配置
    pyqt5安装 + pycharm配置
    Python redis 存取使用
    pycharm 打不开 解决办法
    Python 将图片上传至阿里云OSS对象存储
    mysql表中已有数据,为表新增一个自增id。
    Python 使用BrowserMob Proxy + Selenium 获取Ajax加密数据
    Pycharm 2020.01亲测激活到2089年
    Python3 执行JS出现JSON未定义问题
    pycharm激活,此方法为永久激活。
  • 原文地址:https://www.cnblogs.com/memory4young/p/java-string-stringbuffer-stringbuilder.html
Copyright © 2011-2022 走看看