Skip to content

Commit 050c162

Browse files
authored
Optimize CodedBufferWriter._copyInto to memcpy (#885)
dart2wasm currently can't optimize loops into memcpy, however `setRange` methods have type tests to generate `array.copy` (Wasm's `memcpy`). Replacing the loops in `CodedBufferWriter._copyInto` with `setRange` improves an internal benchmark extracted from a real use case significantly in all targets: | | Before | After | Diff | |------------------------------|------------|------------|---------------------| | AOT | 127,587 us | 95,634 us | -31,953 us, -25.0% | | JIT | 106,880 us | 92,800 us | -14,080 us, -13.1% | | dart2js -O4 | 285,587 us | 262,222 us | -23,365 us, -8.1% | | dart2wasm --omit-type-checks | 337,000 us | 236,100 us | -100,900 us, -29.9% |
1 parent b2b239b commit 050c162

File tree

1 file changed

+8
-11
lines changed

1 file changed

+8
-11
lines changed

protobuf/lib/src/protobuf/coded_buffer_writer.dart

Lines changed: 8 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -421,22 +421,19 @@ class CodedBufferWriter {
421421

422422
/// Copy bytes from the given typed data array into the output buffer.
423423
///
424-
/// Has a specialization for Uint8List for performance.
424+
/// Has a specialization for [Uint8List] for performance.
425425
int _copyInto(Uint8List buffer, int pos, TypedData value) {
426426
if (value is Uint8List) {
427427
final len = value.length;
428-
for (var j = 0; j < len; j++) {
429-
buffer[pos++] = value[j];
430-
}
431-
return pos;
428+
final end = pos + len;
429+
buffer.setRange(pos, end, value);
430+
return end;
432431
} else {
433432
final len = value.lengthInBytes;
434-
final u8 = Uint8List.view(
435-
value.buffer, value.offsetInBytes, value.lengthInBytes);
436-
for (var j = 0; j < len; j++) {
437-
buffer[pos++] = u8[j];
438-
}
439-
return pos;
433+
final end = pos + len;
434+
final u8 = Uint8List.view(value.buffer, value.offsetInBytes, len);
435+
buffer.setRange(pos, end, u8);
436+
return end;
440437
}
441438
}
442439

0 commit comments

Comments
 (0)