AppendCharacterWithChar

AppendCharacterWithChar

本文介绍了在StringBuffer追加中使用字符而不是字符串作为单字符值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在通过PMD规则AppendCharacterWithChar.它说在StringBuffer.append中避免将字符串联为字符串.

I was going through the PMD rule AppendCharacterWithChar. It says Avoid concatenating characters as strings in StringBuffer.append.

StringBuffer sb = new StringBuffer();
  // Avoid this
  sb.append("a");

  // use instead something like this
  StringBuffer sb = new StringBuffer();
  sb.append('a');

我真的需要此PMD规则吗?以下两段代码之间在性能上有很大区别吗?

Do I really need this PMD rule? Is there much performance difference between the following two piece of code?

String text = new StringBuffer().append("some string").append('c').toString();

String text = new StringBuffer().append("some string").append("c").toString();

推荐答案

将字符追加为char总是比将其追加为String更快.

Appending a character as a char will always be faster than appending it as a String.

但是性能差异重要吗?如果只执行一次,则不会.如果它在一个循环中重复其身体一百万次,那么是的,这可能很重要.

But does the performance difference matter? If you just do it once, it doesn't. If it is inside a cycle repeating its body a million times, then yes, it might matter.

如果在编译时已经具有该字符,则只需将其附加为字符即可.如果将其存储在String类型的变量中,请不要麻烦访问它,例如使用String.charAt(0)或其他方式,只需添加String.

If you already have the character at compile time, just append it as a character. If it is stored in a variable with String type, don't bother accessing it e.g. with String.charAt(0) or some other ways, simply just append the String.

附带说明:

喜欢 StringBuilder 类到 StringBuffer . StringBuilder更快,因为它的方法不同步(大多数情况下不需要).

Favor the StringBuilder class to StringBuffer. StringBuilder is faster because its methods are not synchronized (which you don't need in most cases).

在旁注2:

无法编译:

String text = new StringBuffer().append("some string").append('c');

append()返回StringBuffer进行链接.您需要在其上调用toString():

append() returns StringBuffer for chaining. You need to call toString() on it:

String text = new StringBuffer().append("some string").append('c').toString();

这篇关于在StringBuffer追加中使用字符而不是字符串作为单字符值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 23:10