用指定字符填充指定长度的String的最有效方法? [英] Most efficient way to fill a String with a specified length with a specified character?
问题描述
这问题,我的答案就是我问这个问题的原因。我不确定什么是最好的方法来表现明智。
示例
方法签名:
字符串getPattern(int length,char character);
用法:
//返回zzzzzz
getPattern(6,'z');
我所尝试的
字符串getPattern(int长度,字符字符){
字符串结果=;
for(int i = 0; i< length; i ++){
result + = character;
}
返回结果;
}
这是我可以做到最好的表现吗?
您应该使用 StringBuilder ,而不是像这样连接字符。使用 StringBuilder.append()。
StringBuilder会给你更好的表现。串联的问题是你每次创建一个新的String(字符串是不可变的)时,旧的字符串被复制,新的字符串被追加,旧的字符串被抛弃。在一段时间内(比如在一个大的for循环中),会有很多额外的工作会导致性能下降。
Basically given an int, I need to generate a String with the same length containing only the specified character. Related question here, but it relates to C# and it does matter what's in the String.
This question, and my answer to it are why I am asking this one. I'm not sure what's the best way to go about it performance wise.
Example
Method signature:
String getPattern(int length, char character);
Usage:
//returns "zzzzzz"
getPattern(6, 'z');
What I've tried
String getPattern(int length, char character) {
String result = "";
for (int i = 0; i < length; i++) {
result += character;
}
return result;
}
Is this the best that I can do performance-wise?
You should use StringBuilder instead of concatenating chars this way. Use StringBuilder.append().
StringBuilder will give you better performance. The problem with concatenation the way you are doing is each time a new String (string is immutable) is created then the old string is copied, the new string is appended, and the old String is thrown away. It's a lot of extra work that over a period of type (like in a big for loop) will cause performance degradation.
这篇关于用指定字符填充指定长度的String的最有效方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!