缓存对象引用

在编写代码时,您通常需要检索或设置应用程序中各种Forms,Reports,Controls或其他Objects的属性。 通常,使用以下语句来引用这些对象:

strCaption = Forms!("frmTest").cmdButton1.Caption  
对于一个对象的单一引用,您无能为力以加快引用的速度。 另一方面,如果要在某种循环中引用该对象的许多属性,则可以通过将对象变量指向该对象并使用该变量来引用该对象来显着提高速度。宾语。 例如,如果您要引用许多特定控件的属性,则最好使用这样的代码,而不是每次都使用完整的语法来引用控件:

Dim ctl As CommandButton
Set ctl = Forms("frmTest").cmdButton1 
Debug.Print ctl.Name
Debug.Print ctl.Width
'etc... 
在另一个示例中,我将使用ADO Recordset中的特定字段来证明我的观点:

'This would be the slooooower case
Set rst = New ADODB.Recordset
Set rst.ActiveConnection = CurrentProject.Connection
rst.Source = "tblTests"
rst.Open 
For intCounter = 1 to lngSomeReallyBigNumber
  strName = rst.Fields(0).Name
Next intCounter 
'The much faster procedure caches the reference to the Field, as such:
Set rst = New ADODB.Recordset
Set rst.ActiveConnection = CurrentProject.Connection
rst.Source = "tblTests"
rst.Open 
Set fld = rst.Fields(0)
For intCounter = 1 to lngSomeReallyBigNumber
  strName = fld.Name
Next intCounter 
Even in this simple case, in which only a single dot was removed from within the expression, this faster code will take about 40% of the time it took in the slooooower version.
除了前面所述的以外,使用VBA的With..End With语法在代码执行时间上也有相同的改进。

最后,本技巧的关键点是:

对象引用中的点将始终降低代码速度。 您应该尽一切努力减少点数!

From: https://bytes.com/topic/access/insights/712420-cache-object-references

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值