为什么使用整数而不是长?我经常看到Overflow与vba错误有关的问题。我的问题是为什么使用integer变量声明而不是仅仅定义所有数值变量(不包括double等)long?除非您正在执行类似for循环的操作,您可以保证该值不会超过32,767的限制,否则是否会对性能产生影响或其他会导致不使用long?
4 回答
饮歌长啸
TA贡献1951条经验 获得超3个赞
即使这篇文章已有四年历史了,我对此感到好奇并进行了一些测试。最重要的是要注意编码器应该始终将变量声明为SOMETHING。未申报的变量显然表现最差(技术上未申报Variant
)
Long
确实表现最快,所以我不得不认为微软总是建议使用Long
而不是Integer
有意义。我猜测也是如此Byte
,但大多数程序员都没有使用它。
64位WINDOWS 10 LAPTOP的结果
使用代码:
Sub VariableOlymics()'Run this macro as many times as you'd like, with an activesheet ready for data'in cells B2 to D6Dim beginTIME As Double, trials As Long, i As Long, p As Long trials = 1000000000 p = 0 beginTIME = Now For i = 1 To trials Call boomBYTE Next i Call Finished(p, Now - beginTIME, CDbl(trials)) p = p + 1 beginTIME = Now For i = 1 To trials Call boomINTEGER Next i Call Finished(p, Now - beginTIME, CDbl(trials)) p = p + 1 beginTIME = Now For i = 1 To trials Call boomLONG Next i Call Finished(p, Now - beginTIME, CDbl(trials)) p = p + 1 beginTIME = Now For i = 1 To trials Call boomDOUBLE Next i Call Finished(p, Now - beginTIME, CDbl(trials)) p = p + 1 beginTIME = Now For i = 1 To trials Call boomUNDECLARED Next i Call Finished(p, Now - beginTIME, CDbl(trials)) p = p + 1End SubPrivate Sub boomBYTE()Dim a As Byte, b As Byte, c As Byte a = 1 b = 1 + a c = 1 + b c = c + 1End SubPrivate Sub boomINTEGER()Dim a As Integer, b As Integer, c As Integer a = 1 b = 1 + a c = 1 + b c = c + 1End SubPrivate Sub boomLONG()Dim a As Long, b As Long, c As Long a = 1 b = 1 + a c = 1 + b c = c + 1End SubPrivate Sub boomDOUBLE()Dim a As Double, b As Double, c As Double a = 1 b = 1 + a c = 1 + b c = c + 1End SubPrivate Sub boomUNDECLARED() a = 1 b = 1 + a c = 1 + b c = c + 1End SubPrivate Sub Finished(i As Long, timeUSED As Double, trials As Double) With Range("B2").Offset(i, 0) .Value = .Value + trials .Offset(0, 1).Value = .Offset(0, 1).Value + timeUSED .Offset(0, 2).FormulaR1C1 = "=ROUND(RC[-1]*3600*24,0)" End WithEnd Sub
添加回答
举报
0/150
提交
取消