Search code examples
swiftswift3grand-central-dispatchvalue-type

Does parallel programing in swift eliminate value type optimizations?


As I understand it value types in swift can be more performant because they are stored on the stack as opposed to the heap. But if you make many calls to DispatchQueue.sync or DispatchQueue.async does this not render the benefits of value types mute because closures are stored on the heap?


Solution

  • As I understand it value types in swift can be more performant because they are stored on the stack as opposed to the heap.

    Sometimes. Often not. For example, String includes heap-allocated storage. Many value types have hidden heap-allocated storage (this is actually really common). So you may not be getting the performance gain you're expecting for many types, but in many cases you're not losing it via closures either.

    Value types are about behavior, not performance (and of course you need to distinguish between value types and value semantics, which are different, and can have impacts on performance). So the nice thing about value types and DispatchQueue is that you know you're not going to accidentally modify a value on multiple queues, because you know you have your own independent copy. By the time you've paid the overhead of dispatching to a queue (which is optimized, but still not cheap), the extra cost of copying the value type probably is not the major issue.

    In my experience, it is very difficult to reason about Swift performance, particularly due to copy-on-write optimizations. But the fact that apparent "value types" can have hidden internal reference types also make performance analysis very tricky. You often have to know and rely on internal details that are subject to change. To even begin getting your head around Swift performance, you should definitely watch Understand Swift Performance (possibly a couple of times). If you're bringing any performance intuitions from C++, you have to throw almost all of that away for Swift. It just does so many things differently.