提交 a00be62b 编写于 作者: A Arjen Poutsma 提交者: Brian Clozel

Calculating capacity before allocation.

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

Issue: SPR-17558
上级 4955d08f
......@@ -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();
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册