Re: Your thoughts on two item id methods?
- Posted by Michael Nelson <mikestar13 at sbcglobal.net> Oct 18, 2005
- 499 views
Al Getz wrote: >Im looking at something that needs to tell the difference between two >different classes of elements in a loop. The two methods presented >here both work, but they work somewhat different. I'd like to hear >any thoughts anyone has on these two methods, as to which one if any >seems better and why... > >METHOD #1 > >Atoms are of one class, while sequences are of the other class. >Here, we know items of class 1 are atoms, while class 2 items are sequences. >This way we can tell the difference between class 1 items and class 2 items... > >itemlist={ 1,2,3,{8,9},4,{6,7} } --atoms and sequences >for k=1 to length(itemlist) do > item=itemlist[k]--atom or seq > if atom(item) then > DoClass1Stuff(item) > else > DoClass2Stuff(item) > end if >end for > > >METHOD #2 > >Atoms will be in a sequence where the first element is zero, while >the other class will always have a '1' as first element with the real >data in elements 2 and above. Thus, class 1 elements start with a zero >and class 2 elements start with a 1... > >itemlist={ {0,1},{0,2},{0,3},{1,8,9},{0,4},{1,6,7} } --all sequences > >for k=1 to length(itemlist) do > item=itemlist[k]--always a sequence > if item[1] then > DoClass2Stuff(item) > else > DoClass1Stuff(item) > end if >end for > >I'm not that worried about the increase in memory space taken by >the second method. >In each itemlist there will be approx the same number of class 1 items >as there are class 2 items. > Method 1 uses less memory, which you don't care about, but it will also run faster. The atom() type check is extremely fast, probably in the ballpark of an "if variable then" construct, though likely just a bit slower. But it is sure to be faster than "if variable[subscript] then". Also, "DoClassStuff(item)" may need a slice in method 2 than method 1 won't require. However, this is only workable if you will only need to distinguish atom and sequence elements--it does not generalize. Say at some point you need to quickly distinguish ordinary sequences from character strings--now you could prefix the strings with a 2, but method 1 would require you to check the whole element to see if it is a string. -- Mike Nelson