Skip to content
This repository was archived by the owner on Feb 22, 2023. It is now read-only.

Commit fd73f27

Browse files
authored
made ascii string encoding faster (#101777)
1 parent 30a5018 commit fd73f27

File tree

2 files changed

+37
-3
lines changed

2 files changed

+37
-3
lines changed

dev/benchmarks/microbenchmarks/lib/foundation/standard_message_codec_bench.dart

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -92,5 +92,20 @@ void main() {
9292

9393
watch.reset();
9494

95+
watch.start();
96+
for (int i = 0; i < _kNumIterations; i += 1) {
97+
codec.encodeMessage('special chars >\u263A\u{1F602}<');
98+
}
99+
watch.stop();
100+
101+
printer.addResult(
102+
description: 'StandardMessageCodec unicode',
103+
value: watch.elapsedMicroseconds.toDouble() / _kNumIterations,
104+
unit: 'us per iteration',
105+
name: 'StandardMessageCodec_unicode',
106+
);
107+
108+
watch.reset();
109+
95110
printer.printToStdout();
96111
}

packages/flutter/lib/src/services/message_codecs.dart

Lines changed: 22 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -386,9 +386,28 @@ class StandardMessageCodec implements MessageCodec<Object?> {
386386
}
387387
} else if (value is String) {
388388
buffer.putUint8(_valueString);
389-
final Uint8List bytes = utf8.encoder.convert(value);
390-
writeSize(buffer, bytes.length);
391-
buffer.putUint8List(bytes);
389+
final Uint8List asciiBytes = Uint8List(value.length);
390+
Uint8List? utf8Bytes;
391+
int utf8Offset = 0;
392+
// Only do utf8 encoding if we encounter non-ascii characters.
393+
for (int i = 0; i < value.length; i += 1) {
394+
final int char = value.codeUnitAt(i);
395+
if (char <= 0x7f) {
396+
asciiBytes[i] = char;
397+
} else {
398+
utf8Bytes = utf8.encoder.convert(value.substring(i));
399+
utf8Offset = i;
400+
break;
401+
}
402+
}
403+
if (utf8Bytes != null) {
404+
writeSize(buffer, utf8Offset + utf8Bytes.length);
405+
buffer.putUint8List(Uint8List.sublistView(asciiBytes, 0, utf8Offset));
406+
buffer.putUint8List(utf8Bytes);
407+
} else {
408+
writeSize(buffer, asciiBytes.length);
409+
buffer.putUint8List(asciiBytes);
410+
}
392411
} else if (value is Uint8List) {
393412
buffer.putUint8(_valueUint8List);
394413
writeSize(buffer, value.length);

0 commit comments

Comments
 (0)