on Fri Aug 05 2016, KS Sreeram <swift-users-AT-swift.org> wrote:

>> On 05-Aug-2016, at 1:19 PM, Daniel Vollmer <[email protected]> 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.

Create a Sequence that represents the elements you're going to append,
e.g.:

  var a = [1, 2]
  a.reserve(256)
  a += sequence(first: 3, next: {$0 < 1000 ? ($0 + 3) * 2 : nil})

There are lots of ways to make Sequences, but the overloaded sequence()
functions are probably the easiest.

HTH,

-- 
-Dave

_______________________________________________
swift-users mailing list
[email protected]
https://lists.swift.org/mailman/listinfo/swift-users

Reply via email to