FiveTech Support Forums

FiveWin / Harbour / xBase community
Board index FiveWin for Harbour/xHarbour hash vs scan 352 ms / 42953 ms
Posts: 6983
Joined: Fri Oct 07, 2005 07:07 PM
hash vs scan 352 ms / 42953 ms
Posted: Thu Jun 27, 2024 08:31 PM
Hello friends,
LOCAL lhash := .f.

I have source code here to count how often a customer number appears in a list.
I first tried to solve the problem with ascan. However, it is extremely slow. Maybe I have a logical error and it could be accelerated.
Then I tried with a hash.

Using hashes can significantly speed up operations that involve frequent lookups, such as counting occurrences or maintaining mappings.

In my case, the speed difference is 352 ms compared to 42953 ms.

Best regards,
Otto
Code (fw): Select all Collapse
static function CreateSummaryDbf()
    
    LOCAL cDbfPath := "x:\xwhdaten\datawin\BELEGUNG.dbf"
    local hbookings := {=>}
    local I := 0
    local aTmp := ""
    LOCAL aBookings := {}
    LOCAL nKdnr
    LOCAL nCount
    LOCAL lhash := .f.  
    
    use (cDbfPath ) new
    nStartTime := SECONDS()
    do while .not. eof()
        
        if lhash = .t.
            IF HHasKey(hbookings, BELEGUNG->GastNR)
                aTmp := hbookings[ BELEGUNG->GastNR ]
                aTmp[1]  := aTmp[1] + 1
                hbookings[ BELEGUNG->GastNR ] := aTmp
            ELSE
                hbookings[ BELEGUNG->GastNR ] := {  1, "test" }
            ENDIF
            
        ELSE
            I := AScan( abookings, { |a| a[ 1 ] == BELEGUNG->GastNR } )
            
            if I = 0 
                AADD( abookings, { BELEGUNG->GastNR, 1, recno()  } )
            else
                abookings[I,2 ]  := abookings[I,2 ] + 1
            endif
        ENDIF
        
        
        skip
        
    enddo 
     
   if lhash = .t.
        // Convert hash to array for XBROWSE
        FOR EACH nKdnr IN HGetKeys(hBookings)
            AADD(aBookings, { nKdnr, hBookings[nKdnr][1],  hBookings[nKdnr][2]})
        NEXT
    ENDIF
   
    nDuration := (SECONDS() - nStartTime) * 1000 // Dauer in Millisekunden
    // Browse the collected data
    xBrowse(aBookings,  "   Duration: " + STR(nDuration, 10, 2) )
    
return

//----------------------------------------------------------------------------//
Posts: 10733
Joined: Sun Nov 19, 2006 05:22 AM
Re: hash vs scan 352 ms / 42953 ms
Posted: Fri Jun 28, 2024 03:00 PM
In my case, the speed difference is 352 ms compared to 42953 ms.
Yes. Searching a hash by Key is far far faster than AScan.

But at the same time, you can improve the logic for faster results irrespective of using hash or array.
Regards



G. N. Rao.

Hyderabad, India

Continue the discussion