Skip to content
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

Improve byte buffer iteration speed by 90% #664

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 1 addition & 1 deletion Sources/SnapshotTesting/Snapshotting/NSImage.swift
Expand Up @@ -104,7 +104,7 @@ private func compare(_ old: NSImage, _ new: NSImage, precision: Float, perceptua
let newRep = NSBitmapImageRep(cgImage: newerCgImage).bitmapData!
let byteCountThreshold = Int((1 - precision) * Float(byteCount))
var differentByteCount = 0
for offset in 0..<byteCount {
fastForEach(in: 0..<byteCount) { offset in
if oldRep[offset] != newRep[offset] {
differentByteCount += 1
}
Expand Down
12 changes: 11 additions & 1 deletion Sources/SnapshotTesting/Snapshotting/UIImage.swift
Expand Up @@ -123,7 +123,7 @@ private func compare(_ old: UIImage, _ new: UIImage, precision: Float, perceptua
} else {
let byteCountThreshold = Int((1 - precision) * Float(byteCount))
var differentByteCount = 0
for offset in 0..<byteCount {
fastForEach(in: 0..<byteCount) { offset in
if oldBytes[offset] != newerBytes[offset] {
differentByteCount += 1
}
Expand Down Expand Up @@ -249,3 +249,13 @@ final class ThresholdImageProcessorKernel: CIImageProcessorKernel {
}
}
#endif

/// When the compiler doesn't have optimizations enabled, like in test targets, a `while` loop is significantly faster than a `for` loop
/// for iterating through the elements of a memory buffer. Details can be found in [SR-6983](https://github.com/apple/swift/issues/49531)
func fastForEach(in range: Range<Int>, _ body: (Int) -> Void) {
var index = range.lowerBound
while index < range.upperBound {
body(index)
index += 1
}
}