Apache Commons StringUtils.repeat() 是如何工作的以及为什么它以这种方式工作?
how Apache Commons StringUtils.repeat() works and why it works in this way?
我今天才开始使用 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();
}
}
我只是想知道他们出于什么原因将重复分成几个案例?与性能有什么关系吗?
如果我被要求写 'repeat()',我将简单地使用带有 append()
的 FOR 循环
我想知道我能从作者写代码的过程中学到什么。
似乎作者针对几个用例优化了方法,它们 think/know 很常见:一个和两个字符的输入字符串。
这是一个很好的例子,说明为什么使用框架(例如 Commons Lang)来进行这种字符串操作是有益的; API 将隐藏实现细节,这些细节对您或您的同事来说并不总是惯用的或易于阅读,但可能会提高性能。
我今天才开始使用 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();
}
}
我只是想知道他们出于什么原因将重复分成几个案例?与性能有什么关系吗?
如果我被要求写 'repeat()',我将简单地使用带有 append()
我想知道我能从作者写代码的过程中学到什么。
似乎作者针对几个用例优化了方法,它们 think/know 很常见:一个和两个字符的输入字符串。
这是一个很好的例子,说明为什么使用框架(例如 Commons Lang)来进行这种字符串操作是有益的; API 将隐藏实现细节,这些细节对您或您的同事来说并不总是惯用的或易于阅读,但可能会提高性能。