Skip to content

Commit 2b248f9

Browse files
authored
Merge pull request #62143 from eeckstein/optimize-empty-set
Optimize empty Sets which are initialized with array literals
2 parents d3e9659 + 126f3e1 commit 2b248f9

File tree

2 files changed

+38
-0
lines changed

2 files changed

+38
-0
lines changed

stdlib/public/core/Set.swift

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -212,11 +212,17 @@ extension Set: ExpressibleByArrayLiteral {
212212
///
213213
/// - Parameter elements: A variadic list of elements of the new set.
214214
@inlinable
215+
@inline(__always)
215216
public init(arrayLiteral elements: Element...) {
216217
if elements.isEmpty {
217218
self.init()
218219
return
219220
}
221+
self.init(_nonEmptyArrayLiteral: elements)
222+
}
223+
224+
@_alwaysEmitIntoClient
225+
internal init(_nonEmptyArrayLiteral elements: [Element]) {
220226
let native = _NativeSet<Element>(capacity: elements.count)
221227
for element in elements {
222228
let (bucket, found) = native.find(element)

test/SILOptimizer/set.swift

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
// RUN: %target-swift-frontend -parse-as-library -primary-file %s -O -sil-verify-all -module-name=test -emit-sil | %FileCheck %s
2+
// RUN: %target-swift-frontend -parse-as-library -primary-file %s -Osize -sil-verify-all -module-name=test -emit-sil | %FileCheck %s
3+
// REQUIRES: swift_stdlib_no_asserts,optimized_stdlib
4+
// REQUIRES: swift_in_compiler
5+
6+
// Test optimal code generation for creating empty sets.
7+
8+
// CHECK-LABEL: sil @$s4test30createEmptySetFromArrayLiteralShySiGyF
9+
// CHECK: global_addr @_swiftEmptySetSingleton
10+
// CHECK-NOT: apply
11+
// CHECK: } // end sil function '$s4test30createEmptySetFromArrayLiteralShySiGyF'
12+
public func createEmptySetFromArrayLiteral() -> Set<Int> {
13+
return []
14+
}
15+
16+
// CHECK-LABEL: sil @$s4test29createEmptySetWithInitializerShySiGyF
17+
// CHECK: global_addr @_swiftEmptySetSingleton
18+
// CHECK-NOT: apply
19+
// CHECK: } // end sil function '$s4test29createEmptySetWithInitializerShySiGyF'
20+
public func createEmptySetWithInitializer() -> Set<Int> {
21+
return Set<Int>()
22+
}
23+
24+
// CHECK-LABEL: sil @$s4test17createNonEmptySetShySiGyF
25+
// CHECK: global_value
26+
// CHECK: [[F:%[0-9]+]] = function_ref @$sSh21_nonEmptyArrayLiteralShyxGSayxG_tcfCSi_Tg5
27+
// CHECK: apply [[F]]
28+
// CHECK: } // end sil function '$s4test17createNonEmptySetShySiGyF'
29+
public func createNonEmptySet() -> Set<Int> {
30+
return [1, 2, 3]
31+
}
32+

0 commit comments

Comments
 (0)