Skip to content

stdlib: add a shortcut for Array.append(contentsOf:) in case the argument is an Array, too. #29220

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

Merged
merged 1 commit into from
Jan 16, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
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
13 changes: 12 additions & 1 deletion stdlib/public/core/Array.swift
Original file line number Diff line number Diff line change
Expand Up @@ -1220,7 +1220,18 @@ extension Array: RangeReplaceableCollection {
_buffer.count += writtenCount
}

if writtenUpTo == buf.endIndex {
if _slowPath(writtenUpTo == buf.endIndex) {

// A shortcut for appending an Array: If newElements is an Array then it's
// guaranteed that buf.initialize(from: newElements) already appended all
// elements. It reduces code size, because the following code
// can be removed by the optimizer by constant folding this check in a
// generic specialization.
if newElements is [Element] {
_internalInvariant(remainder.next() == nil)
return
}

// there may be elements that didn't fit in the existing buffer,
// append them in slow sequence-only mode
var newCount = _getCount()
Expand Down
17 changes: 17 additions & 0 deletions test/SILOptimizer/array_contentof_opt.swift
Original file line number Diff line number Diff line change
Expand Up @@ -54,3 +54,20 @@ public func testString(_ a: inout [String], s: String) {
public func dontPropagateContiguousArray(_ a: inout ContiguousArray<UInt8>) {
a += [4]
}

// Check if the specialized Array.append<A>(contentsOf:) is reasonably optimized for Array<Int>.

// CHECK-LABEL: sil shared {{.*}}@$sSa6append10contentsOfyqd__n_t7ElementQyd__RszSTRd__lFSi_SaySiGTg5

// There should only be a single call to _createNewBuffer or reserveCapacityForAppend/reserveCapacityImpl.

// CHECK-NOT: apply
// CHECK: [[F:%[0-9]+]] = function_ref @{{.*(_createNewBuffer|reserveCapacity).*}}
// CHECK-NEXT: apply [[F]]
// CHECK-NOT: apply

// The number of basic blocks should not exceed 20 (ideally there are no more than 16 blocks in this function).
// CHECK-NOT: bb20:

// CHECK: } // end sil function '$sSa6append10contentsOfyqd__n_t7ElementQyd__RszSTRd__lFSi_SaySiGTg5