[swift-users] Set size of byte array

KS Sreeram ks at claylabs.com
Fri Aug 5 11:42:59 CDT 2016

> On 05-Aug-2016, at 1:19 PM, Daniel Vollmer <lists at maven.de> wrote:
> I’m by no means a Swift expert (not even a user at the moment), but I don't
> see a way to do this either. The best that comes to mind is initializing a
> ContiguousArray with the sufficient capacity as size, using
> withUnsafeBufferPointer to overwrite elements, and then use replaceAll() with
> an empty collection to remove the excess size.

The only initializer that could help with this is: init(count:repeatedValue:). Unfortunately, this means the buffer is written to twice - once in the initializer, and a second time to actually fill in the data. It’s not efficient.

> I'd think that just reserving enough capacity and then appending the elements
> one-by-one will be (at least?) as efficient: The byte is always copied anyway,
> and in this case you wouldn’t have to default-construct the capacity beforehand.

This too isn’t efficient because each append call will incur an the cost of checking for sufficient capacity and also incrementing the size. The additional penalty could dwarf the cost of actually copying a byte! I don’t think the compiler is capable of removing this inefficiency.

KS Sreeram

More information about the swift-users mailing list