且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

用指定字符填充指定长度的String的最有效方法?

更新时间:2023-02-18 10:20:23

您应该使用 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.