[英]does a replace function internally run an instr
如果我要在经典的ASP页面上执行诸如此类的操作:
if instr(tmp, "®") then tmp = replace(tmp, "®", "®")
if instr(tmp, "™") then tmp = replace(tmp, "™", "™")
if instr(tmp, "©") then tmp = replace(tmp, "©", "©")
替换功能实际上已经在执行内部指令了吗? 如果是这样,应将以上代码简单地更改为:
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
这可能不是最全面的测试,但看来哪种方法更快的答案取决于您是否希望在要替换的字符串中看到搜索字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.