Android StringBuilder vs String Concatenation

前端 未结 2 666
一整个雨季
一整个雨季 2021-02-05 14:24

I was reading this documentation page, http://developer.android.com/reference/android/util/Log.html.

The section here caught my eye:

Tip: Don\'t f

2条回答
  •  醉梦人生
    2021-02-05 14:42

    Ted Hopp's answer is good, but it took reading it a few times to understand. Here is a rephrased answer that is hopefully more clear.

    String concatenation (ie, using +, as in String myString = "Hello " + "World";) uses a StringBuilder in the background along with other allocations. Thus, for anything other than a simple one-time concatenation, it would be better to use a StringBuilder yourself.

    For example,

    StringBuilder myString = new StringBuilder();
    myString.append("Hello ");
    myString.append("to ");
    myString.append("everyone ");
    myString.append("in ");
    myString.append("the ");
    myString.append("world!");
    

    is better than

    String myString = "Hello " + "to " + "everyone " + "in " + "the " + "world!";
    

提交回复
热议问题