Daniel Lemire's blog

, 2 min read

Initializing arrays quickly in Swift: be wary of Sadun’s initializers

3 thoughts on “Initializing arrays quickly in Swift: be wary of Sadun’s initializers”

  1. thanks for sharing and narration

  2. Dennis says:

    Hey Daniel, great tips for initializing arrays with Swift. I am just getting started with programming collaboration tools for the iPhone. It’s great to know that you can optimize performance by avoiding appended elements. Your source code is very helpful.

  3. Michael says:

    Swift recently (in version 5.1) added a way to implement this initializer better. Array.init(unsafeUninitializedCapacity: initializingWith:) It gives direct access to the backing memory buffer of the array, so it can be dangerous if used incorrectly.

    Here is a fast and correct implementation of Erica’s generator using this new feature:

    extension Array {
    public init(count: Int, generator generate: () throws -> Element) rethrows {
    try self.init(unsafeUninitializedCapacity: count) { buffer, initializedCount in
    for i in 0..<count {
    try buffer[i] = generate()
    // initializedCount must be updated in the happy
    // path for the generated objects to be properly
    // deallocated if an error is thrown.
    initializedCount += 1

    This generates much better code than using a lazy map. As shown here.