Page 1 of 1

Improve Code

Posted: Thu Dec 26, 2019 5:09 am
by bpd2000
Hi
How can I improve code using AEval instead of For Next loop

Code: Select all

#include "fivewin.ch"

function Main()

   local aData := {}
   local i, j,  aTemps2 := {}

FOR i := 1 TO  50
    FOR j := 1 TO  26
      aAdd(aTemps2, hb_valtostr("Demo "+alltrim(str(i))+" "+alltrim(str(j))))
    NEXT j
    aAdd( aData,  aTemps2)
    aTemps2 := {}
NEXT i

xbrowser adata

return nil

Re: Improve Code

Posted: Thu Dec 26, 2019 7:43 am
by AntoninoP
Nice quiz, for me this solution should works,

Code: Select all

local aData := Array(50,26)
aEval(aData, {|x,i| aEval(aData[i], {|y,j| aData[i,j]:=hb_valtostr("Demo "+alltrim(str(i))+" "+alltrim(str(j))) })} )
but it spawns an error:

Code: Select all

Error E0005  Outer codeblock variable 'I' is out of reach
that I don't undestand.
but I can fix it, in this way:

Code: Select all

local aData := Array(50,26), i
aEval(aData, {|x,ii| i:=ii, aEval(aData[i], {|y,j| aData[i,j]:=hb_valtostr("Demo "+alltrim(str(i))+" "+alltrim(str(j))) })} )

Re: Improve Code

Posted: Thu Dec 26, 2019 8:53 am
by bpd2000
Thank you

Re: Improve Code

Posted: Thu Dec 26, 2019 9:23 am
by Enrico Maria Giordano
This is the most efficient code, I think:

Code: Select all

#include "fivewin.ch"

function Main()

    local aData[ 50000, 26 ]
    local nSec
    local i, j

    nSec = SECONDS()

    FOR i := 1 TO  50000
        FOR j := 1 TO  26
            aData[ i, j ] = "Demo "+ltrim(str(i))+" "+ltrim(str(j))
        NEXT j
    NEXT i

    ? SECONDS() - nSec

    xbrowser adata

    return nil
EMG

Re: Improve Code

Posted: Fri Dec 27, 2019 6:20 pm
by AntoninoP
Sure, it is better pre-allocate the array of the right size then fill it instead of do aAdd more and more.
If you don't know the final size you can pre-allocate of a big size then use aSize of right dimension, like

Code: Select all

aData:=Array(1000)
j:=1
for i:=1 to 1000
   if( something )
     aData[j++]:= value
   endif
next
aSize(@aData,j)
For a correct measure you should include the array creation.

Re: Improve Code

Posted: Fri Dec 27, 2019 6:37 pm
by Enrico Maria Giordano
AntoninoP wrote:For a correct measure you should include the array creation.
Right. I tried: no change.

EMG