Optimizing execution speed with CollectionOfOne in Swift


Greetings, traveler!

There is a type in Swift called CollectionOfOne, which is a collection of one element. Does it sound weird? Don’t rush to judge.

Check out this example. We can measure the execution time using a benchmark we created in one of the articles.

Note

By the way, if you’d like to learn more about this benchmark, you can do so here.

This function helps us print out the operation’s result value in the console and measure its execution time.

func printCount(of collection: any Collection) {
    let benchmark = Benchmark()
    print(collection.count)
    benchmark.stop()
}

Now, let’s create two collections.

let array = [1]
let collectionOfOne = CollectionOfOne(1)

Now, let’s use our function to print out the count of both collections and check out the measurement result.

printCount(of: array) // 0.02817 sec.
printCount(of: collectionOfOne) // 0.00016 sec.

It looks significant.

We will gain the same result using all methods and variables from the Collection protocol interface. The reason is that CollectionOfOne’s implementation of these methods and variables contains hardcoded values. Like this:

public var count: Int {
  return 1
}

Conclusion

If you want to make your code faster, you can use this type.