Home > other >  Is it possible to add part of list to ByteBuilder without twice copies in dart?
Is it possible to add part of list to ByteBuilder without twice copies in dart?

Time:03-05

For example, I just want to copy the middle 4 elements of src to a ByteBuilder:

import 'dart:typed_data';

void main() async {
  var s1 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
  var src = Uint8List.fromList(s1);
  var bb = BytesBuilder();
  var part = src.sublist(4, 8); // first copy
  bb.add(part); // second copy
  var other = bb.toBytes();
  print("$other");
}

CodePudding user response:

The BytesBuilder will do at least one copy. It has two modes, one where it copies when you add the bytes (but then it might need to grow its buffer occasionally), and one where it just remembers the input and does the copying when you call toBytes (but then changes to the original list, which happens after adding it, will apply to the result as well).

To avoid the second copy, you can use a view on the sub-list instead of creating a copy.

  var part = Uint8List.sublistView(s1, 4, 8);

That creates a view of the slice of s1, but doesn't copy the elements.

If used with the late-copying BytesBuilder, that again means that changes to the original list will bleed through to the result.

For a relatively short sublist (four bytes is very much small), making a copy might be cheaper than creating a view. The copy just needs to hold the actual four bytes and a length, the view needs to refer to the original an contain two integers, which is at least three pointer-sizes of data. For a long slice, the saving can be significant.

  •  Tags:  
  • dart
  • Related