Last night Mike Feltman, of F1 Technologies, did a presentation called "Collections". He discussed the basics of collections and arrays, and very some cool utilities he wrote for working with both.
One of cool things I learned had to do with the FOXOBJ clause of the FOR EACH ... ENDFOR command. For example, in the following code sample "loObject" is not a Visual FoxPro object, but is re-casted as a COM object.
loCollection = CREATEOBJECT("Collection")
loCollection.Add(CREATEOBJECT("Custom"))
FOR EACH loObject IN loCollection
&& loObject is a COM object, AMEMBERS() returns 0.
ENDFOR
Starting with Visual FoxPro 9, we can add the FOXOBJ clause so that loObject is a Visual FoxPro object. This is an important distinction, because functions like AMEMBERS() and COMOBJ() would produce unexpected results.
loCollection = CREATEOBJECT("Collection")
loCollection.Add(CREATEOBJECT("Custom"))
FOR EACH loObject IN loCollection FOXOBJECT
&& loObject is a Visual FoxPro object, AMEMBERS() returns 18.
ENDFOR
The FOXOBJ clause was not new to me. However, what I did not know was that using the FOXOBJ clause made the FOR EACH ... ENDFOR command almost 2x faster than the FOR ... ENDFOR equivalent.
* create a collection with 10,000 items
loCollection = CREATEOBJECT("Collection")
FOR m.lnX = 1 TO 10000
loCollection.Add(CREATEOBJECT("Custom"))
ENDFOR
* test the performance using FOR EACH
m.lnStartTime = SECONDS()
FOR EACH loObject IN loCollection
* do nothing, we already have an object reference
ENDFOR
? "FOR EACH: " + TRANSFORM(SECONDS() - m.lnStartTime) && 0.156 seconds
* test the performance using FOR EACH with FOXOBJ
m.lnStartTime = SECONDS()
FOR EACH loObject IN loCollection FOXOBJ
* do nothing, we already have an object reference
ENDFOR
? "FOR EACH with FOXOBJ: " + TRANSFORM(SECONDS() - m.lnStartTime) && 0.016 seconds
* test the performance using simple FOR
m.lnStartTime = SECONDS()
FOR m.lnX = 1 TO loCollection.COUNT
* get an object reference to the item
loObject = loCollection.ITEM(m.lnX)
ENDFOR
? "FOR: " + TRANSFORM(SECONDS() - m.lnStartTime) && 0.031 seconds
Little gems like this are one of the benefits of attending local FoxPro user groups meetings. The opportunity to learn something new, meet new people, and the comradery are all valuable benefits.
If you missed this presentation, I heard that Mike will be presenting it again at the Grand Rapids Area FoxPro User Group on May 10th, 2008.
Links:
DAFUG http://dafug.org
GRAFUG http://www.grafug.com
F1 Technologies http://www.f1tech.com