Performance impact of using KeyPaths or type metadata at runtime as dictionary keys?

What are some ways I could optimize the performance of using KeyPaths or ObjectedIdentifiers as dictionary keys?

Consider the following two functions:

object identifier lookup function:

var idDict = [ObjectIdentifier: Any]()

func lookup<T>(type: T.Type) -> T? {
    idDict[ObjectIdentifier(T.self)] as? T
}

keyPath lookup function:

var keyPathDict = [AnyKeyPath: Any]()

func lookup<R, V>(path: KeyPath<R, V>) -> V? {
    keyPathDict[path] as? V
}

With these I'm seeing a pretty significant lookup time with stack traces like:

  51 libswiftCore.dylib 1.0  swift::Demangle::NodeFactory::createNode(swift::Demangle::Node::Kind)
  50 libswiftCore.dylib 1.0  swift::_buildDemanglingForContext(swift::TargetContextDescriptor<swift::InProcess> const*, llvm::ArrayRef<swift::Demangle::Node*>, swift::Demangle::Demangler&)
  49 libswiftCore.dylib 1.0  swift::_swift_buildDemanglingForMetadata(swift::TargetMetadata<swift::InProcess> const*, swift::Demangle::Demangler&)
  48 libswiftCore.dylib 1.0  swift::_swift_buildDemanglingForMetadata(swift::TargetMetadata<swift::InProcess> const*, swift::Demangle::Demangler&)
  47 libswiftCore.dylib 1.0  _swift_initClassMetadataImpl(swift::TargetClassMetadata<swift::InProcess>*, swift::ClassLayoutFlags, unsigned long, swift::TypeLayout const* const*, unsigned long*, bool)
  46 libswiftCore.dylib 1.0  type metadata completion function for _DictionaryStorage
  45 libswiftCore.dylib 1.0  swift_getGenericMetadata
  44 libswiftCore.dylib 1.0  __swift_instantiateGenericMetadata
  43 libswiftCore.dylib 1.0  _swift_getKeyPath(pattern:arguments:)
  42 AnalysisHarness 1.0  performanceTest() 

Just curious whether there's a more performant way to store and lookup values based on a keypath than using a dictionary.

1 Like
Terms of Service

Privacy Policy

Cookie Policy