Skip to content

Instantly share code, notes, and snippets.

@numist
Created March 6, 2013 07:36
Show Gist options
  • Save numist/5097441 to your computer and use it in GitHub Desktop.
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.
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;
};
@numist
Copy link
Author

numist commented Mar 6, 2013

Here's a comparison against some other algorithms, y-axis is time, x axis is sample number, samples ordered by elapsed time:

Performance graph of five different image comparison approaches in Objective-C

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment