问题描述
我正在编写一个Dart库,在其中我经常处理字节数组或字节字符串.由于Dart没有字节类型也没有数组类型,因此我将List用于所有字节数组.
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.
这是一个好习惯吗?我只是最近才发现dart:typed_data
包中是否存在Uint8List
.显然,该类旨在通过字节数组的转到实现来实现.
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?
还有一个名为ByteArray的类,但是对于List来说,它似乎是一个效率很低的替代方法.
There also is a class named ByteArray, but it seems to be a quite inefficient alternative for List...
推荐答案
优点应该是Uint8List比普通List消耗更少的内存,因为从一开始就知道每个元素的大小都是一个字节.Uint8List也可以直接映射到基础优化的Uint8List类型(例如,在Javascript中).列表切片的副本也更容易执行,因为所有字节都是内存中的布局字符串,因此可以通过一次操作将切片直接复制到另一个Uint8List(或等效的)类型.
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.
但是,能否充分利用此优势取决于Dart中Uint8List的实现情况.
However if this advantage is fully used depends on how good the implementation of Uint8List in Dart is.
这篇关于使用Uint8List而不是List< int>的优势是什么?在Dart中处理字节数组时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!