Is there a more efficent way to do this?

I’m iterating over two slightly different images and getting differences between pixels that happen to differ.

I’m checking for equality first, and then going in and getting the absolute difference between pixels if they do differ. I think this is about as efficient as I can reasonably get it without hyper-optimizing while going through the first phase of developing my project, but I’m somewhat inexperienced. Is there a better way to do this? Is checking for inequality first before getting the absolute difference if I only expect about 5% of pixels to differ the right move?

	for cnt := range fr.PixelBytes {

		//Hopefully, checking for non-equal and then doing the math for exact basdiff later helps wih performance
		if fr.PixelBytes[cnt] != reference.PixelBytes[cnt] {

			absDiff := 0
			frb := fr.PixelBytes[cnt]
			ref := reference.PixelBytes[cnt]

			if frb > ref {
				absDiff = frb - ref
			} else {
				absDiff = ref - frb
			byteDiffCount += absDiff

You should be a little better off capturing those values when you do the comparison so you don’t have to fetch them again. Also, math.Abs uses bitshifting to remove the negative bit, that should be a little faster than your comparison using the intermediate var. So:

if frb, ref := fr.PixelBytes[cnt], reference.PixelBytes[cnt]; frb != ref {
    byteDiffCount += math.Abs(frb - ref)
1 Like