arraysdartuint8t

What are the advantages of using Uint8List over List<int> when dealing with byte arrays in Dart?


I'm writing a Dart library in which I'm very regularly dealing with byte arrays or byte strings. Since Dart doesn't have a byte type nor an array type, I'm using List for all byte arrays.

Is this a good practice to do? I only recently found out about the existence of Uint8List in the dart:typed_data package. It's clear that this class aims to by the go-to implementation for byte arrays.

But does it have any direct advantages?

I can imagine that it does always perform checks on new items so that the user can make sure no non-byte-value integers are inside the list. But are there other advantages or differences?

There also is a class named ByteArray, but it seems to be a quite inefficient alternative for List...


Solution

  • The advantage should be that the Uint8List consumes less memory than a normal List, because it is known from the beginning that each elements size is a single byte. Uint8List can also be mapped directly to underlying optimized Uint8List types (e.g. in Javascript). Copies of list slices are also easier to perform, because all bytes are laid-out continguos in memory and therefore the slice can be directly copied in a single operation to another Uint8List (or equivalent) type.

    However if this advantage is fully used depends on how good the implementation of Uint8List in Dart is.