Member-only story
Swift High Performance: Dictionary Keys
I improved Factory’s dictionary lookup performance by over 500%! Can you do the same in your app?

This article is an in-depth exploration of how to create dictionary keys that are fast and performant under all circumstances, and why String-based keys often fail in that regard.
It includes actual examples and performance data taken from Factory, my open-source dependency injection library.
Ready? Let’s get into it.
Caching
A common practice in any application is to create some expensive item, cache that item in a key-based dictionary, and then check later on to see if that item exists, returning the cached value if it does.
An extremely rudimentary implementation of that might be:
class ItemRepository {
private var cache = [String:Item]()
func item(forKey key: String) -> Item? {
if let item = cache[key] {
return item
}
let item = Item(key: key)
cache[key] = item
return item
}
}
We’ve all seen or done some variation of this.
But the fundamental problem we have here is that using a Swift String
as our dictionary key isn’t an optimal choice. Far…