[swift-users] Set size of byte array

Arnold Schwaighofer aschwaighofer at apple.com
Tue Aug 9 14:38:13 CDT 2016


> On Aug 9, 2016, at 12:07 PM, Joe Groff <jgroff at apple.com> wrote:
> 
> 
>> On Aug 5, 2016, at 9:42 AM, KS Sreeram via swift-users <swift-users at swift.org> wrote:
>> 
>> 
>>> 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.
> 
> cc-ing Arnold, who owns this part of the optimizer. IIRC we are able to hoist the capacity check in 'append' loops in some cases.
> 

The optimizer is not currently doing an optimization based on semantic knowledge of reserveCapacity(), the number of appends called, and capacity() calls.

Without that the optimizer just sees a load of the capacity field which is (conditionally) written to by the append call and therefore not loop invariant.



More information about the swift-users mailing list