Thursday, February 7, 2019

Fast Safe Mutable State in Swift 5

Ben Cohen:

My talk from Functional Swift Conf about some of the performance challenges with Collections of Copy-on-Write types, and how we’ve fixed this in the standard library in Swift 5.

Ben Cohen:

Here’s the code for Dictionary’s subscript _modify

What Dictionary does is find the key, then move the corresponding value out of its buffer temporarily into an optional it then yields. This leaves an uninitialized hole in the buffer memory – but that’s fine, because subscript call keeps exclusive access to that memory.

The caller can then modify that optional in-place, and the value inside it remains uniquely referenced. Then the caller returns from the yield, and dictionary can move the element back into its storage before returning.

This is using unsafe operations under the hood (to move the memory out of the buffer) but only the bottom layer needs to do this. You can then layer more yielding subscripts on top of it (as Dictionary does here – the unsafe stuff is isolated in _NativeDictionary).

And the unsafe ops are all regular std lib operations using UnsafeMutablePointer. No scary builtins involving pinning memory in place.

Previously:

Comments RSS · Twitter

Leave a Comment