« REALbasic Developer M… | Home | A QuickLook Plugin fo… »

Speed optimization in REALbasic Code.

Today someone asked why this code is very slow:
// Methods
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>
now calling len(mem) here does the following:
  • Create a copy of the memoryblock as a string.
  • Lookup the length of this string.
  • Destroy the string.
And this happens all 128 million times! This takes forever. The solution is easy: Use mem.size instead of len(mem) you can save a magnitude of time. Also you should keep the upper bound of the for loop in a local variable for even faster code:
Sub Better()
// 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
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:
Sub Best()
// 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
PS: Code formatted with my format script: monkeybreadsoftware.de/realbasic/format.shtml Claris FileMaker Plugin
04 05 10 - 15:12