Hi 4tH-ers!
Normally, the 4tH preprocessor is speedy enough, but sometimes, there is a noticeable delay. Not enough to irritate you, but still.
So I wondered if I could speed things up by applying binary search with some lookup tables. But would it do enough?
Well, I decided to test the thing, took a long (200+ entries) table and started a long line of random lookups (>100,000). Then I calculated the speedup the use of binary search achieved.
The first graph shows you the speedup. With 200 elements, it's over 7 times as fast. The "cutt-off" point is around 10 elements. A lower number of elements and binary search is even slower. The graph passes the "two times faster" line at 50 elements.
The second one shows the number of milliseconds to do a search. The binary search line is almost flat (even flatter than I expected) while the sequential search is exponential (as expected).
BOTTOMLINE: You're crazy NOT to use binary search if you have more than 50 elements. Between 25 and 50 elements it really depends on how often the table is searched, but don't expect any miracles. Below 25, just do a sequential search.
In PP4TH the biggest table counts 45 elements. That's just in between, so I figured it wouldn't be worth the trouble - because binary search is hard to set up (may be I ought to make that easier).
Finally, for your listening pleasure, the code (minus the table).
include lib/bsearch.4th
include lib/row.4th
include lib/anstools.4th
include lib/choose.4th
64 string (search-key) does> >r r@ place r> ;
create Brands \ tabel met toegestane merknamen
(...)
here Brands - constant #Brands
NULL ,
: bsBrands ( a1 n1 a2 n2 -- a3 f)
['] b-compare defer@ >r ['] get-key defer@ >r
:noname swap cells + @c ; is get-key \ key-retrieval functie
:noname >r count r> count compare ; is b-compare
>r >r (search-key) r> r> bsearch
r> is get-key r> is b-compare \ perform a binary search
;
( a1 n1 a2 -- a1 n1 a3 f)
: sqBrands >r (search-key) count r> 1 string-key row ;
: rndBrand Brands #Brands choose cells + @c count ;
: rndBs rndBrand Brands #Brands bsBrands drop drop ;
: rndSq rndBrand Brands sqBrands drop drop 2drop ;
: testBs 0 ?do rndBs loop ;
: testSq 0 ?do rndSq loop ;
#Brands . cr
400000 testSq
Hans Bezemer
