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

时间:2014-07-11 03:39:04

标签: vbscript asp-classic

如果我在经典的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语句中包含用户内容等等......

1 个答案:

答案 0 :(得分:3)

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

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

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