在我们写VBA程序的时候,我们经常要面对数据类型定义的选择,有的情况下,业务本身对于数据类型有要求和限制,那么我们并不难以选择,有些时候却没有限制,我们可以任意选用四种整数类型(Byte,Integer,Long,Currency)中的一种,例如:
For i=1 to 100
在这行代码中,我们该把变量i定义为什么类型的变量呢?显然四种整数类型都可以正常运行,但是他们的效率是否相同呢?我们到底该如何选择?有的人说,当时是选最小的数据类型Byte,有的人说在32位系统上,32位的Long类型才是效率最高的。
那么究竟谁说的是正确的,让我们来进行一下这四种整数类型的性能对比测试,我们使用如下代码:
Const LoopTimes = 100000000
Public Sub test()
Dim bytTmp As Byte
Dim intTmp As Integer
Dim lngTmp As Long
Dim curTmp As Currency
Dim loopCount As Long
Dim timeBegin As Single
Dim timeEnd As Single
Dim timeAddition As Single
timeBegin = Timer
For loopCount = 0 To LoopTimes
Next loopCount
timeEnd = Timer
timeAddition = timeEnd - timeBegin
timeBegin = Timer
For loopCount = 0 To LoopTimes
bytTmp = 255
Next loopCount
timeEnd = Timer
Debug.Print "Byte :"; timeEnd - timeBegin - timeAddition; "秒"timeBegin = Timer
For loopCount = 0 To LoopTimes
intTmp = 255
Next loopCount
timeEnd = Timer
Debug.Print "Integer :"; timeEnd - timeBegin - timeAddition; "秒"timeBegin = Timer
For loopCount = 0 To LoopTimes
lngTmp = 255
Next loopCount
timeEnd = Timer
Debug.Print "Long :"; timeEnd - timeBegin - timeAddition; "秒"timeBegin = Timer
For loopCount = 0 To LoopTimes
curTmp = 255
Next loopCount
timeEnd = Timer
Debug.Print "Currency :"; timeEnd - timeBegin - timeAddition; "秒"
Debug.Print "*********************"End Sub
在这里,我们对每个整数类型进行了1亿次的赋值操作,同时减去了循环控制所消耗的空转时间,剩下的就是纯粹的赋值操作所需的时间。最后,让我们来看看运行的结果:
Byte : 7.234375 秒
Integer : 2.421875 秒
Long : 3.4375 秒
Currency : 4.84375 秒
*********************
Byte : 7.234375 秒
Integer : 2.421875 秒
Long : 3.453125 秒
Currency : 4.875 秒
*********************
Byte : 7.21875 秒
Integer : 2.421875 秒
Long : 3.421875 秒
Currency : 4.875 秒
*********************