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: some 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
}A Note on Benchmarking
However, it’s important to note that this measurement is not entirely rigorous. In such a simplified micro-benchmark, the compiler may aggressively optimize the code — including constant folding, inlining, or even eliminating parts of the computation altogether. When both the input and the iteration count are known at compile time, the entire loop can sometimes be reduced to a constant in the generated assembly. For more reliable results, it’s better to use a dedicated benchmarking framework, rely on tools like Instruments (Time Profiler or Processor Trace), and verify in the assembly that the computation you intend to measure is actually being executed. Micro-benchmarks are easy to fool — real workloads provide much stronger evidence.
Conclusion
CollectionOfOne is a specialized type with a highly optimized implementation for a very specific use case. In scenarios where a collection of exactly one element is required, it can be more efficient than allocating a full array. However, performance decisions should always be guided by profiling real workloads rather than relying solely on simplified micro-benchmarks.
