The Swift Cooperative

Authors publishing advanced articles on Swift and SwiftUI application development.

Follow publication

Member-only story

Swift High Performance: Dictionary Keys

Michael Long
The Swift Cooperative
11 min readAug 27, 2023

Photo by Chunli Ju on Unsplash

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…

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

The Swift Cooperative
The Swift Cooperative

Published in The Swift Cooperative

Authors publishing advanced articles on Swift and SwiftUI application development.

Michael Long
Michael Long

Written by Michael Long

I write about Apple, Swift, and SwiftUI in particular, and technology in general. I'm also a Lead iOS Engineer at InRhythm, a modern digital consulting firm.

Responses (9)

Write a response

that is an impressive performance boost. but what is missing from the article is a paragraph on when to use this — and when not. I'd argue that if the app only performs a few lookups per second (let's say: up to a few ten thousand), the gains in…

I much enjoyed your detailed and guided way of discussion this advanced topic. It shows how easy it is to make code that in the long run could be faster. Thanks for sharing all the steps you took to optimize it. A delight to read and we will enjoy to the performance boost once 2.3 comes out!

Hey Michael, Thanks for the post. I have question regarding an architecture i developed for our app core product list page. I have maintained cache using uuid string and value being the corresponding item for collection compositonal layout's…