[swift-users] How to malloc in Swift 3
Gerriet M. Denkmann
gerrietm at me.com
Sat Sep 24 22:36:23 CDT 2016
> On 23 Sep 2016, at 19:41, Quinn The Eskimo! via swift-users <swift-users at swift.org> wrote:
>
>
> On 23 Sep 2016, at 11:29, Gerriet M. Denkmann via swift-users <swift-users at swift.org> wrote:
>
>> What about calloc then? Or use allocate and do a memset afterwards?
>
> For trivial data types (like UInt8) this will work, but if you want to follow the rules I recommend reading the following:
>
> * UnsafeRawPointer Migration
>
> <https://swift.org/migration-guide/se-0107-migrate.html>
>
> * SE-0107 “UnsafeRawPointer API”
>
> <https://github.com/apple/swift-evolution/blob/master/proposals/0107-unsaferawpointer.md>
>
> Spoiler: that’ll point you to `initialize(to:count:)` (-:
Thanks for the links.
By the way: I had already tried to use `initialize(to:count:)` before, but I used it as a replacement of allocate, which the compiler did not really like.
Since reading these documents I know that I have to use it after allocate, not instead of.
In dealloc I had before:
free( bitfield )
which, to my surprise, the compiler did NOT warn about (should there be a warning?)
I have since replace this with:
bitfield.deallocate(capacity: numberUsedInAllocate )
> * * *
>
> Also, why are you manually allocating this rather than using [UInt8]? The latter is easier, safer, and likely to have similar levels of efficiency.
I just tried this: [UInt8] turns out to be nearly 10% slower compared to: UnsafeMutablePointer<UInt8>.allocate(capacity:).
Probably depends on the use case, whether 10% less performance is worth the easier and safer.
I am trying to compare Swift to ObjC classes (which use malloc), so it would not be a fair comparison if the Swift class has to use an UInt8 array.
Kind regards,
Gerriet.
More information about the swift-users
mailing list