Java Apache Commons StringUtils.repeat()是如何工作的,以及为什么它以这种方式工作?

Java Apache Commons StringUtils.repeat()是如何工作的,以及为什么它以这种方式工作?,java,apache,apache-commons,Java,Apache,Apache Commons,我今天刚开始使用apache commons库,发现他们编写repeat() 以下是该方法的源代码: public static String repeat(final String str, final int repeat) { if (str == null) { return null; } if (repeat <= 0) { return EMPTY; } final int inputLength = s

我今天刚开始使用apache commons库,发现他们编写
repeat()

以下是该方法的源代码:

public static String repeat(final String str, final int repeat) {
    if (str == null) {
        return null;
    }
    if (repeat <= 0) {
        return EMPTY;
    }
    final int inputLength = str.length();
    if (repeat == 1 || inputLength == 0) {
        return str;
    }
    if (inputLength == 1 && repeat <= PAD_LIMIT) {
        return repeat(str.charAt(0), repeat);
    //here the author use FOR loop with char[]
    }

    final int outputLength = inputLength * repeat;
    switch (inputLength) {
        case 1 :
            return repeat(str.charAt(0), repeat);
        case 2 :
            final char ch0 = str.charAt(0);
            final char ch1 = str.charAt(1);
            final char[] output2 = new char[outputLength];
            for (int i = repeat * 2 - 2; i >= 0; i--, i--) {
                output2[i] = ch0;
                output2[i + 1] = ch1;
            }
            return new String(output2);
        default :
            final StringBuilder buf = new StringBuilder(outputLength);
            for (int i = 0; i < repeat; i++) {
                buf.append(str);
            }
            return buf.toString();
    }
}
publicstaticstringrepeat(finalstringstr,finalint repeat){
如果(str==null){
返回null;
}

if(repeat似乎作者针对他们认为/知道的几个常见用例优化了该方法:一个和两个字符的输入字符串


这是一个很好的例子,说明了为什么使用框架(如Commons Lang)是有益的对于这种类型的字符串操作,API将隐藏实现细节,这些细节并不总是惯用的,也不容易为您或您的同事阅读,但可能会提高性能。

我相信这是性能。大多数人只会编写一个带有for循环的stringbuffer.Micro-optimization。如果
str
的长度为一个或两个字符呃,使用了一种不同的更快的模式。@Bubletan你能解释一下为什么当长度为1or2时,不同的模式可以更快吗?@pledez不同的模式对于其他长度也可能更快,但是对于所有不同的情况,单独写出来是没有意义的。我认为,根据你的回答和@Bubletan的评论,可能是从一个角度从统计学的角度来看,程序员最常使用一到两个字符的重复,因此作者专门编写了这两个优化案例。@pledez,或者更确切地说,这是作者的假设。