Page 1 of 1

If possible don't use recursive functions

Posted: Mon Jul 11, 2005 3:38 pm
by Psychophanta
Code updated for 5.20+

Here is a tip to get the min and max float value from a list of them. (no ASM used).
There is a recursive version and a normal loop based version for each one.
Recursive functions are much slower than normal ones. Tested.
You can compare speed and demonstrate it to yourself.
That is due to the heavy stack mem management in recursive functions.

Code: Select all

Procedure.f MinF(n1.f,n2.f)
  If n1<n2:ProcedureReturn n1:EndIf
  ProcedureReturn n2
EndProcedure

Procedure.f MaxF(n1.f,n2.f)
  If n1>n2:ProcedureReturn n1:EndIf
  ProcedureReturn n2
EndProcedure

Procedure.f MinFMultiple(*base.float,amount.l);<- no recursive
  result.f=*base\f
  While amount>1
    *base+SizeOf(float)
    result=MinF(*base\f,result)
    amount-1
  Wend
  ProcedureReturn result
EndProcedure

Procedure.f MinFMultiple0(*base.float,amount.l);<- recursive
  result.f=*base\f
  If amount>1
    *base+SizeOf(float)
    result=MinF(MinFMultiple0(*base,amount-1),result)
  EndIf
  ProcedureReturn result
EndProcedure

Procedure.f MaxFMultiple(*base.float,amount.l);<- no recursive
  result.f=*base\f
  While amount>1
    *base+SizeOf(float)
    result=MaxF(*base\f,result)
    amount-1
  Wend
  ProcedureReturn result
EndProcedure

Procedure.f MaxFMultiple0(*base.float,amount.l);<- recursive
  result.f=*base\f
  If amount>1
    *base+SizeOf(float)
    result=MaxF(MaxFMultiple0(*base,amount-1),result)
  EndIf
  ProcedureReturn result
EndProcedure

Structure g
  tt.f[160]
EndStructure

var.g
For t.l=0 To 159
  var\tt[t]=Random(100000000)/100000
Next

For t.l=0 To 159
  Debug var\tt[t]
Next

Debug"---"

Debug MinFMultiple0(@var\tt[0],160)
Debug MinFMultiple(@var\tt[0],160)
Debug MaxFMultiple0(@var\tt[0],160)
Debug MaxFMultiple(@var\tt[0],160)
BTW: I haven't found any explicit and simple recursive function demonstration in the CodeArchive at purearea.net :!:
If there are not should be good to include the typical factorial:

Code: Select all

Procedure.l factorial(n.l)
  If n>2
    n*factorial(n-1)
  EndIf
  ProcedureReturn n
EndProcedure

Debug factorial(6)

Posted: Mon Jul 11, 2005 6:06 pm
by dracflamloc
There are some algorithms which are faster via recursion...but not many, and its usually a pain in the ass to write anyway

Posted: Mon Jul 11, 2005 6:11 pm
by Psychophanta
dracflamloc wrote:There are some algorithms which are faster via recursion...but not many, and its usually a pain in the ass to write anyway
yeah :lol: