Calculating capacity before allocation.

This commit optimizes the `CharSequenceEncoder` to allocate `DataBuffer`
instances with a predicted capacity.

Issue: SPR-17558
This commit is contained in:
Arjen Poutsma 2018-12-20 21:33:50 +01:00 committed by Brian Clozel
parent 4955d08f28
commit a00be62b04
1 changed files with 14 additions and 1 deletions

View File

@ -20,6 +20,8 @@ import java.nio.charset.Charset;
import java.nio.charset.CoderMalfunctionError;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import org.reactivestreams.Publisher;
import reactor.core.publisher.Flux;
@ -49,6 +51,9 @@ public final class CharSequenceEncoder extends AbstractEncoder<CharSequence> {
*/
public static final Charset DEFAULT_CHARSET = StandardCharsets.UTF_8;
private final ConcurrentMap<Charset, Float> charsetToMaxBytesPerChar =
new ConcurrentHashMap<>(3);
private CharSequenceEncoder(MimeType... mimeTypes) {
super(mimeTypes);
@ -76,7 +81,8 @@ public final class CharSequenceEncoder extends AbstractEncoder<CharSequence> {
});
}
boolean release = true;
DataBuffer dataBuffer = bufferFactory.allocateBuffer();
int capacity = calculateCapacity(charSequence, charset);
DataBuffer dataBuffer = bufferFactory.allocateBuffer(capacity);
try {
dataBuffer.write(charSequence, charset);
release = false;
@ -93,6 +99,13 @@ public final class CharSequenceEncoder extends AbstractEncoder<CharSequence> {
});
}
private int calculateCapacity(CharSequence sequence, Charset charset) {
float maxBytesPerChar = this.charsetToMaxBytesPerChar
.computeIfAbsent(charset, cs -> cs.newEncoder().maxBytesPerChar());
float maxBytesForSequence = sequence.length() * maxBytesPerChar;
return (int) Math.ceil(maxBytesForSequence);
}
private Charset getCharset(@Nullable MimeType mimeType) {
if (mimeType != null && mimeType.getCharset() != null) {
return mimeType.getCharset();