optimizing scan over matrix in compare docs