Thread Rating:
  • 1 Vote(s) - 4 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Fast replace$() function
#1
For long time, I've used below replace$() function I created:

Code: (Select All)
Function replace$ (content$, from$, to$)
  content2$ = content$
  flen& = Len(from$): tlen& = Len(to$)
  p& = InStr(content2$, from$)
  If flen& = Len(to$) Then
    Do While p& > 0
      Mid$(content2$, p&, flen&) = to$
      p& = InStr(p& + tlen&, content2$, from$)
    Loop
  Else
    Do While p& > 0
      content2$ = Left$(content2$, p& - 1) + to$ + Mid$(content2$, p& + flen&)
      p& = InStr(p& + tlen&, content2$, from$)
    Loop
  End If
  replace$ = content2$
End Function

But recently I had to do +3000's replaces times +1500 1MB files.
The total replace-process took over 1100 seconds.

When I realized the amount of memory copying going on when constantly rebuilding the content2$ for each replace, I was wondering if _Mem could be an option.
I ended up with below mreplace$() function which got exactly the same job done in less then 45 seconds!!

Code: (Select All)
 Function mreplace$ (content$, from$, to$)
  Dim mp As Long, pp As Long, m As _MEM
  m = _MemNew(Len(content$) * 2): mp = 0: pp = 1
  flen& = Len(from$): tlen& = Len(to$)
  p& = InStr(content$, from$)
  Do While p& > 0
    _MemPut m, m.OFFSET + mp, Mid$(content$, pp, p& - pp): mp = mp + p& - pp
    _MemPut m, m.OFFSET + mp, to$: mp = mp + tlen&: pp = p& + flen&
    p& = InStr(p& + flen&, content$, from$)
  Loop
  _MemPut m, m.OFFSET + mp, Mid$(content$, pp): mp = mp + Len(Mid$(content$, pp))
  content2$ = String$(mp, 0): _MemGet m, m.OFFSET, content2$: _MemFree m
  mreplace$ = content2$
End Function

Take advantage if you run into this issue  Smile
45y and 2M lines of MBASIC>BASICA>QBASIC>QBX>QB64 experience
Reply


Messages In This Thread
Fast replace$() function - by mdijkens - 04-15-2025, 10:00 AM
RE: Fast replace$() function - by bplus - 04-15-2025, 10:34 AM
RE: Fast replace$() function - by hsiangch_ong - 04-18-2025, 06:04 PM
RE: Fast replace$() function - by mdijkens - 04-18-2025, 07:31 PM
RE: Fast replace$() function - by SMcNeill - 04-18-2025, 08:29 PM
RE: Fast replace$() function - by mdijkens - 04-18-2025, 09:08 PM
RE: Fast replace$() function - by SMcNeill - 04-19-2025, 08:48 AM
RE: Fast replace$() function - by madscijr - 04-18-2025, 11:07 PM
RE: Fast replace$() function - by mdijkens - 04-19-2025, 10:19 AM
RE: Fast replace$() function - by hsiangch_ong - 04-19-2025, 05:23 PM
RE: Fast replace$() function - by mdijkens - 04-19-2025, 06:27 PM



Users browsing this thread: 1 Guest(s)