Page 1 of 1

A little observation about ReplaceString

Posted: Thu May 10, 2007 8:27 pm
by Heathen

Code: Select all

Macro test1()
  Str.s = ""
  For x = 1 To 2000
    Str.s + Chr(Random(255))
  Next
  
  
  
  time = ElapsedMilliseconds()
  For x = 1 To 1000
    ReplaceString(Str,"hello","blah")
  Next x
  Debug  "No FindString: "+Str(ElapsedMilliseconds()-time)


  time = ElapsedMilliseconds()
  For x = 1 To 1000
    If FindString(Str,"hello",1)
      ReplaceString(Str,"hello","blah")
    EndIf
  Next x
  Debug "FindString: " + Str(ElapsedMilliseconds()-time)
  
  
EndMacro

Macro test2()
  Str.s = ""
  For x = 1 To 2000
    Str.s + "hello"
  Next
  
  
  
  time = ElapsedMilliseconds()
  For x = 1 To 1000
    ReplaceString(Str,"hello","blah")
  Next x
  Debug "No FindString: " + Str(ElapsedMilliseconds()-time)


  time = ElapsedMilliseconds()
  For x = 1 To 1000
    If FindString(Str,"hello",1)
      ReplaceString(Str,"hello","blah")
    EndIf
  Next x
  Debug "FindString: "+Str(ElapsedMilliseconds()-time)
  
  
EndMacro
Debug "---String does not exist---"
test1()
Debug ""
Debug "---String does exist---"
test2()
As you should see, adding FindString before ReplaceString is much faster in cases where the string does not exist and almost as fast when the string does exist.

Sorry if this has been posted before.