With Winsock1
.RemoteHostIP = "8.8.8.8"
.RemotePort = 88
End With比
Winsock1.RemoteHostIP = "8.8.8.8"
Winsock1.RemotePort = 88更快。
新建From1(窗体),新建Text1(TextBox),Command1(按钮CommandButton),代码:
Private Sub Command1_Click()
Command1.Enabled = False
Dim startTime#, i&, str1$, st21$
' 测试不使用With
startTime = Timer
For i = 1 To 10000
Text1.Text = "Test " & i
Text1.ForeColor = QBColor(i Mod 16)
Text1.Font.Size = 8 + (i Mod 4)
Next i
str1 = "Without With: " & Timer - startTime & " seconds"
' 测试使用With
startTime = Timer
With Text1
For i = 1 To 10000
.Text = "Test " & i
.ForeColor = QBColor(i Mod 16)
.Font.Size = 8 + (i Mod 4)
Next i
End With
str2 = "With With: " & Timer - startTime & " seconds"
MsgBox str1 & vbCrLf & str2
Debug.Print str1 & vbCrLf & str2
Command1.Enabled = True
End Sub运行结果:
Without With: 1.31099999999965 seconds
With With: 1.25999999999814 seconds性能优势
1 减少对象引用查找
2 减少属性访问开销
使用建议
何时使用 With
1 多次访问同一对象的属性或方法时
2 在循环中频繁操作同一对象时
3 对象引用较长或复杂时
注意事项
1 不要过度使用: 对于只访问 1-2 次的对象,使用 With 的性能提升可能不明显
2 保持可读性: 避免过于复杂的嵌套结构
3 作用域: With 块内不能使用 Exit With 来提前退出
