Jump to content

Sky Slate Blueberry Blackcurrant Watermelon Strawberry Orange Banana Apple Emerald Chocolate
Photo

[Tip] Search and Replace a character with null


  • Please log in to reply
2 replies to this topic
SKAN
  • Administrators
  • 9115 posts
  • Last active:
  • Joined: 26 Dec 2005
I needed a faster way for my ShellFileOperation() to replace Pipe character with null.

The Tip: InStr() works as I am searching for right-most pipe

SetBatchLines -1
Loop, %A_WinDir%\System32\*.*, 0 ,0
  sStr .= A_LoopFileLongPath "|"

Len:=StrLen( sStr ), ATC:=A_TickCount

StringReplace, sStr, sStr, |, |, UseErrorLevel
Loop % (cCount := ErrorLevel )
  NumPut( 0, sStr, InStr(sStr,"|",0,[color=Red]0[/color])-1, "Char" )

MsgBox, 0, String Length: %Len%, % (A_TickCount-ATC) "ms to replace " cCount " characters"

kWo4Lk1.png

polyethene
  • Members
  • 5519 posts
  • Last active: May 17 2015 06:39 AM
  • Joined: 26 Oct 2012
I can't explain why but when using a non-null value this alternate method is 15x faster:

SetBatchLines -1

z := 46 ; try 0

Loop, %A_WinDir%\System32\*.*
  list1 .= A_LoopFileLongPath . "|"
list3 := list2 := list1

t1 := A_TickCount

Len := StrLen(list1)
StringReplace, list1, list1, |, |, UseErrorLevel
Loop % cCount := ErrorLevel
  NumPut(z, list1, InStr(list1, "|", 0, 0) - 1, "Char")

t2 := A_TickCount

Loop, % StrLen(list2)
	If (NumGet(list2, A_Index, "UChar") == 0x7c) ; | is \x7C
		NumPut(z, list2, A_Index, "UChar")

t3 := A_TickCount

MsgBox, % "#1: " . t2 - t1 . "`n#2: " . t3 - t2 . "`n`n" . (list1 == list2 ? "Pass" : "Fail")

autohotkey.com/net Site Manager

 

Contact me by email (polyethene at autohotkey.net) or message tidbit


SKAN
  • Administrators
  • 9115 posts
  • Last active:
  • Joined: 26 Dec 2005
In my method, InStr() is fast when replace character is null - because the string length becomes shorter with every loop iteration. ( atleast with special way InStr() sees it )

That is my best guess.

Interesting benchmark, Thanks :D
kWo4Lk1.png