## Speed optimization in REALbasic Code.

Today someone asked why this code is very slow:

// Methodsnow calling len(mem) here does the following:

Sub Slow()

// Takes over 15 minutes here

dim t as integer = ticks

dim mem as MemoryBlock = NewMemoryBlock(128*1024*1024)

dim n as integer

for n=0 to len(mem)

mem.Byte(n)=rnd*255

next n

t = ticks-t

MsgBox str(t/60)+" seconds"

End Sub>

- Create a copy of the memoryblock as a string.
- Lookup the length of this string.
- Destroy the string.

Sub Better()You can even optimize it more by using the Random class and requesting a random value in a given range. Integer math is faster here than double math:

// Takes 27 seconds here

dim t as integer = ticks

dim mem as MemoryBlock = NewMemoryBlock(128*1024*1024)

dim n as integer

dim c as integer = mem.size-1

for n=0 to c

mem.Byte(n)=rnd*255

next n

t = ticks-t

MsgBox str(t/60)+" seconds"

End Sub

Sub Best()PS: Code formatted with my format script: monkeybreadsoftware.de/realbasic/format.shtml

// Takes 21 seconds here

dim t as integer = ticks

dim mem as MemoryBlock = NewMemoryBlock(128*1024*1024)

dim n as integer

dim r as new Random

dim c as integer = mem.size-1

for n=0 to c

mem.Byte(n)=r.InRange(0,255)

next n

t = ticks-t

MsgBox str(t/60)+" seconds"

End Sub

No comments