Best way to initialize a constant UUID?

I'm trying to strike a balance between legibility and efficiency here.

I was looking at the UUID initializers in Godbolt, and there's basically only two: init(uuid:) takes a tuple of 16 ints, and init(uuidString:) takes a string. (There's also the decodable init(from:) but I can't imagine that'd be better in any conceivable way here.)

init(uuidString:) is definitely the more developer-friendly option, as you can just copy-paste the UUID from (and to) wherever. However, even when the string is a string literal and the call is immediately force-unwrapped, this still creates a runtime call to a UUID-string parsing function ($s20FoundationEssentials4UUIDV10uuidStringACSgSSh_tcfC), and then moves the result into the UUID object one byte at a time (using different registers for better ILP).

init(uuid:) is far worse for developer productivity, but it seemed like it could be a more efficient alternative. However, even that doesn't put the numbers directly in the UUID object. Instead, it compiles to something like this:

const char tuple[] = { 0x01, 0x02, ..., 0x10 };
char uuid[16] = {0};

int main() {
  memcpy(uuid, tuple, 16);
  // ...
}

I suppose I could write a #UUIDLiteral macro that takes a StaticString argument and compiles to a call to UUID.init(uuid:), but that seems like unnecessary effort.

Is the overhead from init(uuidString:) generally minimal? Or is there a better way to initialize a constant UUID?

The initializers and parse functions are open source.

The implementation is self.uuid = uuid, but it doesn't use @frozen or @inlinable, and apparently Swift's calling convention will destructure the tuple into 16 arguments. (Possibly the stored property can use a fixed-size array type in the future.)

I don't know ā€” it uses sscanf to initialize the tuple elements.

The best of both worlds would probably be a macro that parses the string at compile time and emit code using the tuple initializer.

As a nice side effect you would get compile time errors for malformed UUID strings.

On the other hand, Iā€™m not sure I can imagine a project that uses so many hardcoded UUIDs that the effort is worth it.

3 Likes