Does Swift's UnsafeMutablePointer<Float>.allocate(…) actually allocate memory?

与世无争的帅哥 提交于 2020-01-03 20:57:18

问题


I'm trying to understand Swift's unsafe pointer API for the purpose of manipulating audio samples.

The non-mutable pointer variants (UnsafePointer, UnsafeRawPointer, UnsafeBufferPointer) make sense to me, they are all used to reference previously allocated regions of memory on a read-only basis. There is no type method "allocate" for these variants

The mutable variants (UnsafeMutablePointer, UnsafeMutableRawPointer), however, are documented as actually allocating the underlying memory. Example from the documentation for UnsafeMutablePointer (here):

static func allocate(capacity: Int)

Allocates uninitialized memory for the specified number of instances of type Pointee

However, there is no mention that the UnsafeMutablePointer.allocate(size) can fail so it cannot be actually allocating memory. Conversely, if it does allocate actual memory, how can you tell if it failed?

Any insights would be appreciated.


回答1:


I decided to test this. I ran this program in CodeRunner:

import Foundation

sleep(10)

While the sleep function was executing, CodeRunner reported that this was taking 5.6 MB of RAM on my machine, making our baseline.

I then tried this program:

import Foundation

for _ in 0..<1000000 {
    let ptr = UnsafeMutablePointer<Float>.allocate(capacity: 1)
}

sleep(10)

Now, CodeRunner reports 5.8 MB of RAM usage. A little more than before, but certainly not the extra 4 MB that this should have taken up.

Finally, I assigned something to the pointer:

import Foundation

for _ in 0..<1000000 {
    let ptr = UnsafeMutablePointer<Float>.allocate(capacity: 1)
    ptr.pointee = 0
}

sleep(10)

Suddenly, the program is taking up 21.5 MB of RAM, finally giving us our expected RAM usage increase, although by a larger amount than what I was expecting.

Making a profile in CodeRunner to compile with the optimizations turned on did not seem to make a difference in the behavior I was seeing.

So, surprisingly enough, it does appear that the call to UnsafeMutablePointer.allocate actually does not immediately allocate memory.



来源:https://stackoverflow.com/questions/47806012/does-swifts-unsafemutablepointerfloat-allocate-actually-allocate-memory

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!