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:
parent
4955d08f28
commit
a00be62b04
|
@ -20,6 +20,8 @@ import java.nio.charset.Charset;
|
||||||
import java.nio.charset.CoderMalfunctionError;
|
import java.nio.charset.CoderMalfunctionError;
|
||||||
import java.nio.charset.StandardCharsets;
|
import java.nio.charset.StandardCharsets;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
import java.util.concurrent.ConcurrentHashMap;
|
||||||
|
import java.util.concurrent.ConcurrentMap;
|
||||||
|
|
||||||
import org.reactivestreams.Publisher;
|
import org.reactivestreams.Publisher;
|
||||||
import reactor.core.publisher.Flux;
|
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;
|
public static final Charset DEFAULT_CHARSET = StandardCharsets.UTF_8;
|
||||||
|
|
||||||
|
private final ConcurrentMap<Charset, Float> charsetToMaxBytesPerChar =
|
||||||
|
new ConcurrentHashMap<>(3);
|
||||||
|
|
||||||
|
|
||||||
private CharSequenceEncoder(MimeType... mimeTypes) {
|
private CharSequenceEncoder(MimeType... mimeTypes) {
|
||||||
super(mimeTypes);
|
super(mimeTypes);
|
||||||
|
@ -76,7 +81,8 @@ public final class CharSequenceEncoder extends AbstractEncoder<CharSequence> {
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
boolean release = true;
|
boolean release = true;
|
||||||
DataBuffer dataBuffer = bufferFactory.allocateBuffer();
|
int capacity = calculateCapacity(charSequence, charset);
|
||||||
|
DataBuffer dataBuffer = bufferFactory.allocateBuffer(capacity);
|
||||||
try {
|
try {
|
||||||
dataBuffer.write(charSequence, charset);
|
dataBuffer.write(charSequence, charset);
|
||||||
release = false;
|
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) {
|
private Charset getCharset(@Nullable MimeType mimeType) {
|
||||||
if (mimeType != null && mimeType.getCharset() != null) {
|
if (mimeType != null && mimeType.getCharset() != null) {
|
||||||
return mimeType.getCharset();
|
return mimeType.getCharset();
|
||||||
|
|
Loading…
Reference in New Issue