Skip to content

Commit 548ba33

Browse files
committed
[benchmark] Add DictionarySwapOfObjects
Another dictionary benchmark with objects as key and value types.
1 parent 4e43f74 commit 548ba33

File tree

2 files changed

+45
-0
lines changed

2 files changed

+45
-0
lines changed

benchmark/single-source/DictionarySwap.swift

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,3 +44,47 @@ func swappedCorrectly(swapped: Bool, _ p25: Int, _ p75: Int) -> Bool {
4444
return swapped && (p25 == 75 && p75 == 25) ||
4545
!swapped && (p25 == 25 && p75 == 75)
4646
}
47+
48+
class Box<T : Hashable where T : Equatable> : Hashable {
49+
var value: T
50+
51+
init(_ v: T) {
52+
value = v
53+
}
54+
55+
var hashValue : Int {
56+
return value.hashValue
57+
}
58+
}
59+
60+
extension Box : Equatable {
61+
}
62+
63+
func ==<T: Equatable>(lhs: Box<T>, rhs: Box<T>) -> Bool {
64+
return lhs.value == rhs.value
65+
}
66+
67+
@inline(never)
68+
public func run_DictionarySwapOfObjects(N: Int) {
69+
let size = 100
70+
var dict = Dictionary<Box<Int>, Box<Int>>(minimumCapacity: size)
71+
72+
// Fill dictionary
73+
for i in 1...size {
74+
dict[Box(i)] = Box(i)
75+
}
76+
CheckResults(dict.count == size,
77+
"Incorrect dict count: \(dict.count) != \(size).")
78+
79+
var swapped = false
80+
for _ in 1...10000*N {
81+
swap(&dict[Box(25)]!, &dict[Box(75)]!)
82+
swapped = !swapped
83+
if !swappedCorrectly(swapped, dict[Box(25)]!.value, dict[Box(75)]!.value) {
84+
break
85+
}
86+
}
87+
88+
CheckResults(swappedCorrectly(swapped, dict[Box(25)]!.value, dict[Box(75)]!.value),
89+
"Dictionary value swap failed")
90+
}

benchmark/utils/main.swift

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -129,6 +129,7 @@ precommitTests = [
129129
"DictionaryRemove": run_DictionaryRemove,
130130
"DictionaryRemoveOfObjects": run_DictionaryRemoveOfObjects,
131131
"DictionarySwap": run_DictionarySwap,
132+
"DictionarySwapOfObjects": run_DictionarySwapOfObjects,
132133
"ErrorHandling": run_ErrorHandling,
133134
"GlobalClass": run_GlobalClass,
134135
"Hanoi": run_Hanoi,

0 commit comments

Comments
 (0)