Is concatenating with an empty string to do a string conversion really that bad?

后端 未结 9 912
别那么骄傲
别那么骄傲 2020-12-03 04:45

Let\'s say I have two char variables, and later on I want to concatenate them into a string. This is how I would do it:

char c1, c2;
// ...

Str         


        
相关标签:
9条回答
  • 2020-12-03 05:02

    I prefer using String.valueOf for single conversions - but in your case you really want concatenation.

    However, I would suggest that this version would remove all potential ambiguity:

    String s = c1 + "" + c2;
    

    That way there's no possibility, however remote, of someone considering whether c1 and c2 will be added together before the concatenation.

    0 讨论(0)
  • 2020-12-03 05:06

    Your arguments are good; this is one of the more expressive areas of the Java language, and the "" + idiom seems well entrenched, as you discovered.

    See String concatenation in the JLS. An expression like

    "" + c1 + c2
    

    is equivalent to

    new StringBuffer().append(new Character(c1).toString())
                      .append(new Character(c2).toString()).toString()
    

    except that all of the intermediate objects are not necessary (so efficiency is not a motive). The spec says that an implementation can use the StringBuffer or not. Since this feature is built into the language, I see no reason to use the more verbose form, especially in an already verbose language.

    0 讨论(0)
  • 2020-12-03 05:14

    Unless your app needs every ounce of performance, write the code that's quicker to write and easier to read. "" + is a slower-to-execute syntax, but it certainly seems easier to read every time I've used it.

    0 讨论(0)
提交回复
热议问题