Skip to content

Commit 59b663f

Browse files
mbrandonwejensenstephencelis
authored
Improve the speed of comparing memory buffers by using a workaround t… (#812)
* Improve the speed of comparing memory buffers by using a workaround to a missed compiler optimization Co-authored-by: Eric Jensen <[email protected]> * Update NSImage.swift * Update UIImage.swift * fix --------- Co-authored-by: Eric Jensen <[email protected]> Co-authored-by: Stephen Celis <[email protected]>
1 parent 4862d48 commit 59b663f

File tree

2 files changed

+16
-4
lines changed

2 files changed

+16
-4
lines changed

Sources/SnapshotTesting/Snapshotting/NSImage.swift

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -118,8 +118,14 @@
118118
let newRep = NSBitmapImageRep(cgImage: newerCgImage).bitmapData!
119119
let byteCountThreshold = Int((1 - precision) * Float(byteCount))
120120
var differentByteCount = 0
121-
for offset in 0..<byteCount {
122-
if oldRep[offset] != newRep[offset] {
121+
// NB: We are purposely using a verbose 'while' loop instead of a 'for in' loop. When the
122+
// compiler doesn't have optimizations enabled, like in test targets, a `while` loop is
123+
// significantly faster than a `for` loop for iterating through the elements of a memory
124+
// buffer. Details can be found in [SR-6983](https://github.com/apple/swift/issues/49531)
125+
var index = 0
126+
while index < byteCount {
127+
defer { index += 1 }
128+
if oldRep[index] != newRep[index] {
123129
differentByteCount += 1
124130
}
125131
}

Sources/SnapshotTesting/Snapshotting/UIImage.swift

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -140,8 +140,14 @@
140140
} else {
141141
let byteCountThreshold = Int((1 - precision) * Float(byteCount))
142142
var differentByteCount = 0
143-
for offset in 0..<byteCount {
144-
if oldBytes[offset] != newerBytes[offset] {
143+
// NB: We are purposely using a verbose 'while' loop instead of a 'for in' loop. When the
144+
// compiler doesn't have optimizations enabled, like in test targets, a `while` loop is
145+
// significantly faster than a `for` loop for iterating through the elements of a memory
146+
// buffer. Details can be found in [SR-6983](https://github.com/apple/swift/issues/49531)
147+
var index = 0
148+
while index < byteCount {
149+
defer { index += 1 }
150+
if oldBytes[index] != newerBytes[index] {
145151
differentByteCount += 1
146152
}
147153
}

0 commit comments

Comments
 (0)