Skip to content

draft: Improve map performance through unsafe uninitialized capacity #83297

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 11 additions & 11 deletions stdlib/public/core/Collection.swift
Original file line number Diff line number Diff line change
Expand Up @@ -1199,18 +1199,18 @@ extension Collection {
return []
}

var result = ContiguousArray<T>()
result.reserveCapacity(n)

var i = self.startIndex

for _ in 0..<n {
result.append(try transform(self[i]))
formIndex(after: &i)
return try unsafe Array<T>(unsafeUninitializedCapacity: n) { (
Copy link
Contributor

@stephentyrone stephentyrone Jul 26, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@glessard I assume we'll update this to use an OutputSpan-based init once that's feasible?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That would be preferable indeed.

storage: inout UnsafeMutableBufferPointer<T>,
initializedCount: inout Int
) throws(E) -> Void in
var collectionIndex = self.startIndex
for bufferIndex in 0 ..< n {
unsafe storage[bufferIndex] = try transform(self[collectionIndex])
formIndex(after: &collectionIndex)
initializedCount += 1
}
_expectEnd(of: self, is: collectionIndex)
}

_expectEnd(of: self, is: i)
return Array(result)
}

// ABI-only entrypoint for the rethrows version of map, which has been
Expand Down