Level Extreme platform
Subscription
Corporate profile
Products & Services
Support
Legal
Français
What is the best way to compare two ARRAYS?
Message
From
10/12/1997 18:46:02
 
General information
Forum:
Visual FoxPro
Category:
Other
Miscellaneous
Thread ID:
00064972
Message ID:
00065154
Views:
42
>>>>I want to compare two arrays to see if one
>>>>is different. What is the best way?
>>>
>>>Try the following in a function. llresult will return .T. if the arrays are identical.
>>>
>>>LPARAMETERS parray1, parray2
>>>
>>>LOCAL llresult, lnlast1, lnlast2, lni
>>>lnlast1 = ALEN(parray1)
>>>lnlast2 = ALEN(parray2)
>>>lni = 0
>>>llresult = (lnlast1 = lnlast2)
>>>DO WHILE llresult AND lni < lnlast
>>> lni = lni + 1
>>> llresult = (parray1[lni] = parray2[lni])
>>>ENDDO
>>>RETURN llresult
>>>
>>>hth,
>>>
>>>George
>>
>>
>>I would change it slightly to improve performance by letting vfp do the incrementing and letting the user select starting the compare loop at the bottom if that is where the difference is most likely to occur (need speed!!):
>>
>>LPARAMETERS parray1, parray2, top_bottom
>>
>> if parameters() < 3
>> top_bottom = 0 && start at top (1)
>> endif
>>
>> LOCAL lnlast1, lnlast2, lni
>>
>> lnlast1 = ALEN(parray1)
>> lnlast2 = ALEN(parray2)
>>
>> do case
>>

The most important potential speed improvement is the ability to check from the end of the arrays if that is the most likely source of differences. The worst case would be the last records are different. Starting at the end would make it much faster.
>> case (lnlast1 != lnlast2)
>> return .f.
>>
>> case top_bottom != 0
>>
>> for lni = lnLast1 to 1 step -1
>> if (parray1[lni] != parray2[lni])
>> return .f.
>> endif
>> endfor
>>
>> otherwise
>>
>> for lni = 1 to lnLast1
>> if (parray1[lni] != parray2[lni])
>> return .f.
>> endif
>> endfor
>>
>> endcase
>>
>> RETURN .t.
>
>Albert,
>
>I'd say that in the vast majority of cases, the speed difference is miniscule. Ed's solution wouldn't be the least bit faster (in fact, might be in some cases slower) because of the repeated evaIuation those three functions. In those cases where it was, my gut reaction would be to perhaps look for another solution.
>
>In general, unless there's a quantifiable reason to do so, I never jump out of loops (leaves junk on the runtime stack) via RETURN or EXIT, and my functions and procedures (for the sake of readability) have only a single exit point, the last line. There are exceptions, but IMHO, I wouldn't think this is one of them.
>
>George
Previous
Next
Reply
Map
View

Click here to load this message in the networking platform