Created
March 6, 2013 07:36
-
-
Save numist/5097441 to your computer and use it in GitHub Desktop.
Assuming you have CGImageRefs already, this is—so far—the fastest method I've found to compare them. If you don't have CGImageRefs, the process of manufacturing them may well wipe out all your time savings over other options available to you.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
static BOOL (^imagesDifferByCGDataProviderComparison)(CGImageRef, CGImageRef) = ^(CGImageRef a, CGImageRef b) { | |
BOOL result = NO; | |
CGDataProviderRef aDataProvider = CGImageGetDataProvider(a); | |
CGDataProviderRef bDataProvider = CGImageGetDataProvider(b); | |
// It turns out that the CGDataProvider's pages are set copy-on-write, so these calls are not nearly as expensive as you think. | |
CFDataRef aData = CGDataProviderCopyData(aDataProvider); | |
CFDataRef bData = CGDataProviderCopyData(bDataProvider); | |
if (CFDataGetLength(aData) != CFDataGetLength(bData)) { | |
result = YES; | |
} | |
if (!result) { | |
// memcmp represents 95+% of the time spent in this block. | |
result = !!memcmp(CFDataGetBytePtr(aData), CFDataGetBytePtr(bData), CFDataGetLength(aData)); | |
// If you think you can do better than memcmp by striding over the buffers, you're probably going to have to use assembler to prove it. | |
} | |
CFRelease(aData); | |
CFRelease(bData); | |
return result; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Here's a comparison against some other algorithms, y-axis is time, x axis is sample number, samples ordered by elapsed time:
Thanks to @andymatuschak for the idea of using the CGDataProviders, and @boredzo for the idea of using a CGBitmapContext, the second-fastest approach in the graph above.