A little observation about ReplaceString

Share your advanced PureBasic knowledge/code with the community.
Heathen
Enthusiast
Enthusiast
Posts: 498
Joined: Tue Sep 27, 2005 6:54 pm
Location: At my pc coding..

A little observation about ReplaceString

Post 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.
I love Purebasic.