diff --git a/packages/flutter/lib/src/foundation/serialization.dart b/packages/flutter/lib/src/foundation/serialization.dart index 7fccb62cbe..2b8cd3e40c 100644 --- a/packages/flutter/lib/src/foundation/serialization.dart +++ b/packages/flutter/lib/src/foundation/serialization.dart @@ -13,10 +13,14 @@ import 'dart:typed_data'; /// The byte order used is [Endian.host] throughout. class WriteBuffer { /// Creates an interface for incrementally building a [ByteData] instance. - factory WriteBuffer() { + /// [startCapacity] determines the start size of the [WriteBuffer] in bytes. + /// The closer that value is to the real size used, the better the + /// performance. + factory WriteBuffer({int startCapacity = 8}) { + assert(startCapacity > 0); final ByteData eightBytes = ByteData(8); final Uint8List eightBytesAsList = eightBytes.buffer.asUint8List(); - return WriteBuffer._(Uint8List(8), eightBytes, eightBytesAsList); + return WriteBuffer._(Uint8List(startCapacity), eightBytes, eightBytesAsList); } WriteBuffer._(this._buffer, this._eightBytes, this._eightBytesAsList); diff --git a/packages/flutter/lib/src/services/message_codecs.dart b/packages/flutter/lib/src/services/message_codecs.dart index a03053a62e..0154487236 100644 --- a/packages/flutter/lib/src/services/message_codecs.dart +++ b/packages/flutter/lib/src/services/message_codecs.dart @@ -310,7 +310,7 @@ class StandardMessageCodec implements MessageCodec { ByteData? encodeMessage(Object? message) { if (message == null) return null; - final WriteBuffer buffer = WriteBuffer(); + final WriteBuffer buffer = WriteBuffer(startCapacity: 64); writeValue(buffer, message); return buffer.done(); } diff --git a/packages/flutter/test/foundation/serialization_test.dart b/packages/flutter/test/foundation/serialization_test.dart index e86b0ad202..c2b6e9542d 100644 --- a/packages/flutter/test/foundation/serialization_test.dart +++ b/packages/flutter/test/foundation/serialization_test.dart @@ -124,5 +124,11 @@ void main() { write.done(); expect(() => write.done(), throwsStateError); }); + test('empty WriteBuffer', () { + expect(() => WriteBuffer(startCapacity: 0), throwsAssertionError); + }); + test('size 1', () { + expect(() => WriteBuffer(startCapacity: 1), returnsNormally); + }); }); }