Optimizing Collections in Swift
This repository contains the sample code from the book Optimizing Collections.
In this book, we show how to write very efficient Swift collection code. Throughout the book, we benchmark everything — with some surprising results. We implement custom data structures with value semantics and copy-on-write behavior such as sorted arrays, binary trees, red-black trees, and B-trees.
Even if you never implement your own collections, this book helps you reason about the performance of Swift code.
This repository includes the full source code of every algorithm discussed in the book:
MyOrderedSet: A rudimentary Swift wrapper for the
NSOrderedSetclass in Foundation.
SortedArray: A simple collection storing elements in a sorted array, with O(n) insertions.
AlgebraicTree: A purely functional implementation of red-black trees using algebraic data types.
COWTree: A procedural, structs-and-classes variant of red-black trees that implements the copy-on-write optimization.
BTree: An implementation of in-memory B-trees, based on my
As a bonus, all five data structures implement
BidirectionalCollection, and they all have full value semantics.
Note that while this repository contains nice illustrations of various coding techniques, I don't recommend you use any of this code in your own projects. I had to cut some corners to make sure the code remains relatively easy to understand; full implementations would include lot more functionality that would just obfuscate my point here. For example, none of these collections implement support for removing elements, or in fact any of method in
SetAlgebra other than
For production-ready implementations of ordered collections, please check out my BTree package instead.
You can watch the video of my talk at dotSwift 2017 about optimizing collections by clicking on the image below.
My slides are available on Speaker Deck.
The custom microbenchmarking app I wrote to generate my charts is called Attabench, and it is available in a separate repository. The insertion benchmark I demonstrated is included in the app by default, so you can easily reproduce my results on your own computer.
Tip: try implementing your own optimization ideas, and race them with my code! I'm sure you'll easily beat me if you try.