Monday, December 23, 2019

Swift’s CollectionOfOne

Bruno Rocha:

The cases where using CollectionOfOne is the best approach possible is when you are forced to operate on Collections. In the Standard Library for example, CollectionOfOne is used to insert elements in specific positions of an Array:

public mutating func insert(_ newElement: __owned Element, at i: Int) {
  _checkIndex(i)
  self.replaceSubrange(i..<i, with: CollectionOfOne(newElement))
}

Because replaceSubrange replaces a Collection with another one, cases where the replacement is only a single element can greatly benefit from using CollectionOfOne.

1 Comment RSS · Twitter

Micro optimizations are always fun to read about (and code up). Objective-C / Foundation has had these kinds of specialized collections for a very long time. If you create an NSArray with a single element you actually get back an instance of __NSSingleObjectArrayI through the magic of class clustering.

Personally I'd hate to write code that directly references specialized classes like CollectionOfOne in all but the most dire of situations– certainly not just to avoid typing an append() call! But maybe Swift inlining can squeeze out better performance than Objective-C if you directly use things like CollectionOfOne? Still, I'd prefer that the compiler or framework transparently swap in these optimized classes.

Leave a Comment