Unverified Commit fd73f273 authored by gaaclarke's avatar gaaclarke Committed by GitHub

made ascii string encoding faster (#101777)

parent 30a50180
......@@ -92,5 +92,20 @@ void main() {
watch.reset();
watch.start();
for (int i = 0; i < _kNumIterations; i += 1) {
codec.encodeMessage('special chars >\u263A\u{1F602}<');
}
watch.stop();
printer.addResult(
description: 'StandardMessageCodec unicode',
value: watch.elapsedMicroseconds.toDouble() / _kNumIterations,
unit: 'us per iteration',
name: 'StandardMessageCodec_unicode',
);
watch.reset();
printer.printToStdout();
}
......@@ -386,9 +386,28 @@ class StandardMessageCodec implements MessageCodec<Object?> {
}
} else if (value is String) {
buffer.putUint8(_valueString);
final Uint8List bytes = utf8.encoder.convert(value);
writeSize(buffer, bytes.length);
buffer.putUint8List(bytes);
final Uint8List asciiBytes = Uint8List(value.length);
Uint8List? utf8Bytes;
int utf8Offset = 0;
// Only do utf8 encoding if we encounter non-ascii characters.
for (int i = 0; i < value.length; i += 1) {
final int char = value.codeUnitAt(i);
if (char <= 0x7f) {
asciiBytes[i] = char;
} else {
utf8Bytes = utf8.encoder.convert(value.substring(i));
utf8Offset = i;
break;
}
}
if (utf8Bytes != null) {
writeSize(buffer, utf8Offset + utf8Bytes.length);
buffer.putUint8List(Uint8List.sublistView(asciiBytes, 0, utf8Offset));
buffer.putUint8List(utf8Bytes);
} else {
writeSize(buffer, asciiBytes.length);
buffer.putUint8List(asciiBytes);
}
} else if (value is Uint8List) {
buffer.putUint8(_valueUint8List);
writeSize(buffer, value.length);
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment