Skip to content

Commit 9d99ce5

Browse files
committed
Further optimize the single-element case for Joiner, to eliminate char copying.
1 parent 2e189c0 commit 9d99ce5

File tree

1 file changed

+27
-8
lines changed

1 file changed

+27
-8
lines changed

mug/src/main/java/com/google/mu/util/stream/Joiner.java

Lines changed: 27 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -171,7 +171,7 @@ static final class FasterStringJoiner {
171171
private final String prefix;
172172
private final String suffix;
173173
private int count;
174-
private String last;
174+
private String outstanding;
175175

176176
FasterStringJoiner(String prefix, String delim, String suffix) {
177177
this.buffer = new StringJoiner(delim, prefix, suffix);
@@ -180,26 +180,45 @@ static final class FasterStringJoiner {
180180
}
181181

182182
void add(String str) {
183-
buffer.add(str);
184-
last = str;
185183
count++;
184+
if (prefix.isEmpty() && suffix.isEmpty()) {
185+
if (count == 1) {
186+
outstanding = str;
187+
return;
188+
}
189+
if (count == 2) {
190+
buffer.add(outstanding);
191+
outstanding = null;
192+
}
193+
}
194+
buffer.add(str);
186195
}
187196

188197
FasterStringJoiner merge(FasterStringJoiner that) {
198+
flushOutstanding();
199+
that.flushOutstanding();
189200
this.buffer.merge(that.buffer);
190201
this.count += that.count;
191-
if (that.last != null) {
192-
this.last = that.last;
193-
}
194202
return this;
195203
}
196204

197205
@Override public String toString() {
198206
if (prefix.isEmpty() && suffix.isEmpty()) {
199-
if (count == 0) return "";
200-
if (count == 1) return last;
207+
if (count == 0) {
208+
return "";
209+
}
210+
if (count == 1) {
211+
return outstanding;
212+
}
201213
}
202214
return buffer.toString();
203215
}
216+
217+
private void flushOutstanding() {
218+
if (outstanding != null) {
219+
buffer.add(outstanding);
220+
outstanding = null;
221+
}
222+
}
204223
}
205224
}

0 commit comments

Comments
 (0)