Data operations

The goal is to avoid allocations.

Right, but you have to check your assumptions here. For example, it seems obvious that withUnsafe[Mutable]Bytes(_:) wouldn’t allocate, but that’s not necessarily the case. If the data is discontiguous, then asking for a pointer to a buffer will trigger an allocation, whereas more abstract mechanisms may not.

Speaking of discontiguous data, historically that was feasible, by bridging a dispatch_data_t to an NSData to a Data, but this post indicates that no longer happens. Which really brings me to my main point here: If you absolutely want to avoid allocations, none of this stuff will work for you, because the allocation pattern of these calls is not documented API but an implementation detail.

You seem to have two choices here:

  • You can continue using Data, making sure to use code paths that avoid allocations, and then profile your usage to check that your assumptions are valid.

  • You can switch to a type that has documented memory allocation behaviour.

With regards the second point, you might want to take a look at SwiftNIO’s ByteBuffer type. I’ve not used it myself, but from what I’ve read it seems to be well aligned with your requirements.

Share and Enjoy

Quinn “The Eskimo!” @ DTS @ Apple

2 Likes