Low-level swift optimization tips

The table data can come from anywhere really, it can be some existing, eg yuv videostream or shared Metal resource, but it can also create its own managed data, loaded from an image file, or be part of another table, etc. It's just a simple but useful data type that I have added functionality to as needed, wrapping functionality from vImage, drawing on it via a CGContext etc.


Yes, but it is very rare that I have the need for a separate x and y, and I don't like to always break them up into that or convert them into a tuple, just to access a pixel.

I'm kind of aware of this and hence I've asked questions like this here before.

The reason for why I use them here is just because:

  • There are so many places where we need some kind of vector like data types, eg a Point, a Vector, the origin and size of a Rect, etc, etc. And it's crazy that I shouldn't just be able to eg iterate through all the Vector2<Int> positions of a Rect2D<Int> bounds of a pixel image and access a pixel via subscripting it with that Vector2<Int> point directly. (The Table code i posted here is simplified/stripped, it has dependency of my custom Vector types, Rect<Int>, etc). So I've experimented a lot with various generic Vector types over the years but always ended up in the time consuming rabbit hole of exploring (the optimizability, limits and rough areas of) Swift's generics and protocols.

  • So, after having spent way to much time during these years trying to build a reasonably nice generic Vector (static array) type with type level Count/Index etc, ever since Swift came out actually, never being entirely satisfied, always thinking that it takes too much time, always frustrated by the awkwardness of using CGPoint, CGRect, et al, I sometimes kind of just give up and use the SIMDN types for everything, just to get something done. Then I see what the project really needs and replace the SIMDN types with the simplest possible custom generic Vector variation I can come up with for that project (trying not to begin exploring again).

  • In the Table code here, I have replaced my own Vector2<Int> types with SIMD2<Int> to easily strip it from its most complicated dependency.


So, my current approach is to use some such custom generic Vector types, instead of the SIMDN types (except where using SIMDN types are motivated), with convenient conversions between these, the SIMDN types and CGPoint, CGRect or whatever I have to interface with at some places.

1 Like