StrBuilder
Reusable String Builder - StrBuilder
Introduction
In the StringBuilder
provided by the JDK, string concatenation becomes more efficient and flexible, but generating a new string requires rebuilding the StringBuilder
object, which results in performance loss and memory waste. Therefore, Hutool provides a reusable StrBuilder
.
Usage
StrBuilder
has the same usage as StringBuilder
, except that it has a reset
method to rebuild a new string without allocating new memory.
StrBuilder builder = StrBuilder.create();
builder.append("aaa").append("你好").append('r');
// Result: aaa你好r
Performance Test for Building Strings Multiple Times
We simulated creating 1,000,000 strings to compare the performance of the two, using TimeInterval
timing:
// StringBuilder
TimeInterval timer = DateUtil.timer();
StringBuilder b2 = new StringBuilder();
for (int i = 0; i < 1000000; i++) {
b2.append("test");
b2 = new StringBuilder();
}
Console.log(timer.interval());
// StrBuilder
TimeInterval timer = DateUtil.timer();
StrBuilder builder = StrBuilder.create();
for (int i = 0; i < 1000000; i++) {
builder.append("test");
builder.reset();
}
Console.log(timer.interval());
The test result is:
StringBuilder: 39ms
StrBuilder : 20ms
The performance is almost doubled. Users are welcome to test it themselves.