zoukankan      html  css  js  c++  java
  • Effective Java 51 Beware the performance of string concatenation

    Using the string concatenation operator repeatedly to concatenate n strings requires time quadratic in n. It's an unfortunate consequence of fact that strings are immutable(Item 15).

    // Inappropriate use of string concatenation - Performs horribly!

    public String statement() {

    String result = "";

    for (int i = 0; i < numItems(); i++)

    result += lineForItem(i); // String concatenation

    return result;

    }

       

    To achieve acceptable performance, use a StringBuilder in place of a String

    public String statement() {

    StringBuilder b = new StringBuilder(numItems() * LINE_WIDTH);

    for (int i = 0; i < numItems(); i++)

    b.append(lineForItem(i));

    return b.toString();

    }

       

    Summary

    Don't use the string concatenation operator to combine more than a few strings unless performance is irrelevant. Use StringBuilder's append method instead. Alternatively, use a character array, or process the strings one at a time instead of combining them.

       

  • 相关阅读:
    初涉Django与MySQL连接
    Mysql数据库操作常用命令
    解决远程登录MYSQL数据库
    全集网影片下载
    LR学习资料
    LR性能测试说明
    fiddler
    Axure(快速原型设计工具)
    httpwatch
    Appscan(安全性测试工具)
  • 原文地址:https://www.cnblogs.com/haokaibo/p/beware-the-performance-of-string-concatenation.html
Copyright © 2011-2022 走看看