替换函数是否在内部运行一个instr



如果我在一个经典的ASP页面上执行这些操作:

if instr(tmp, "®") then tmp = replace(tmp, "®", "®")
if instr(tmp, "™") then tmp = replace(tmp, "™", "™")
if instr(tmp, "©") then tmp = replace(tmp, "©", "©")

是替换函数实际上已经做一个内部instr无论如何??如果是这样,是否应该将上面的代码改为:

tmp = replace(tmp, "®", "®")
tmp = replace(tmp, "™", "™")
tmp = replace(tmp, "©", "©")

什么更有效率?它们被用于各种场景,例如在SQL语句中包装用户内容等。

对于性能问题,最好的答案通常是基准测试。幸运的是,这种情况比较容易测试:

Option Explicit
Const testString = "Some moderately long text string. Since I don't know long the actual input is, I'm just going to write some stuff. Oh, look, it's a special character! -> ®"
' Might want to start off with a lower number like 1000 and go up from there
Const numberOfIterations = 1000000
Dim replaceTime, inStrReplaceTime
Dim notReplaceTime, notInStrReplaceTime
' When search string is found in the target string
replaceTime = TestReplace("®")
inStrReplaceTime = TestInStrReplace("®")
' When search string is NOT found in the target string
notReplaceTime = TestReplace("©")
notInStrReplaceTime = TestInStrReplace("©")
WScript.Echo "Results (seconds, lower is better):" & vbNewline & _
    "  Replace: " & replaceTime & vbNewline & _
    "  InStr + Replace: " & inStrReplaceTime & vbNewline & _
    "  Replace (not in string): " & notReplaceTime & vbNewline & _
    "  InStr + Replace (not in string): " & notInStrReplaceTime & vbNewline
Function TestReplace(str)
    Dim startTime, i, outString
    startTime = Timer
    For i = 1 To numberOfIterations
        outString = Replace(testString, str, "something")
    Next
    TestReplace = Timer - startTime
End Function
Function TestInStrReplace(str)
    Dim startTime, i, outString
    startTime = Timer
    For i = 1 To numberOfIterations
        If InStr(testString, str) <> 0 Then outString = Replace(testString, str, "something")
    Next
    TestInStrReplace = Timer - startTime
End Function

在我的机器上,这个脚本给出了如下输出:

Results (seconds, lower is better):
  Replace: 0.8515625
  InStr + Replace: 1.234375
  Replace (not in string): 0.6796875
  InStr + Replace (not in string): 0.3046875

这可能不是最全面的测试,但似乎哪种方法的答案更快取决于您是否希望在您要替换的字符串中看到您的搜索字符串

相关内容

最新更新