Error._domain computation is ineffective

Error.localizedDescription is widely used in many iOS apps.

But it's calculation needs converting Error to NSError using _swift_stdlib_bridgeErrorToNSError function that calls Error._domain computed-property through _getErrorDomainNSString<A>(_:) call.

Error._domain uses String(reflecting: type(of: self)) that internally performs multiple casts to protocols in OutputStream.swift: CustomDebugStringConvertible, CustomStringConvertible, TextOutputStreamable and CustomReflectable inside Mirror initializer. First conformance check for each pair of (class, protocol) is time-consuming because we need to scan all protocol conformance type descriptors.

That's why calculation Error._domain takes 15 ms on launch. Screenshot from Time Profilers traces is attached:

But internally, String(reflecting:) called on metatype eventually calls _typeName(:qualified:) function with qualified: true.

Full call-stack:

  1. Error._domain
  2. String(reflecting:)
  3. _debugPrint_unlocked. Because Any.Type does not conform any of checked protocols.
  4. _adHocPrint_unlocked
  5. _adHocPrint_unlocked.printTypeName

Is there any reason not to use _typeName(:qualified:) directly? It's has no performance-overhead like _debugPrint_unlocked (because of its protocol conformances checks).

Swift issue

1 Like