摘自adambear的《真没想到VB也可以这样用之指针技术》其中一个示例程序: 3、对数组进行批量操作 用指针进行大批量数组数据的移动,从效率上考虑是很有必要的,看下面的两个程序,它们功能都是将数组的前一半数据移到后一半中: 【程序九】: '标准的移动数组的做法 Private Sub ShitArray(ab() As MyType) Dim i As Long, n As Long n = CLng(UBound(ab) / 2) For i = 1 To n Value(n + i) = Value(i) Value(i).data = 0 Next End Sub 【程序十】: '用指针的做法 Private Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" _ (ByVal dest As Long, ByVal source As Long, ByVal bytes As Long) Private Declare Sub ZeroMemory Lib "kernel32" Alias "RtlZeroMemory" _ (ByVal dest As Long, ByVal numbytes As Long) Private Declare Sub FillMemory Lib "kernel32" Alias "RtlFillMemory" _ (ByVal dest As Long, ByVal Length As Long, ByVal Fill As Byte) Private Sub ShitArrayByPtr(ab() As MyTpye) Dim n As Long n = CLng(UBound(ab) / 2) Dim nLenth As Long nLenth = Len(Value(1)) 'DebugBreak CopyMemory ByVal VarPtr(Value(1 + n)), ByVal VarPtr(Value(1)), n * nLenth ZeroMemory ByVal VarPtr(Value(1)), n * nLenth End Sub 当数组较大,移动操作较多(比如用数组实现HashTable)时程序十比程序九性能上要好得多。 程序十中又介绍两个在指针操作中会用到的API: ZeroMemory是用来将内存清零;FillMemory用同一个字节来填充内存。当然,这两个API的功能,也完全可以用CopyMemory来完成。象在C里一样,作为一个好习惯,在VB里我们也可以明确的用ZeroMemory来对数组进行初始化,用FillMemory在不立即使用的内存中填入怪值,这有利于调试。
3、对数组进行批量操作 用指针进行大批量数组数据的移动,从效率上考虑是很有必要的,看下面的两个程序,它们功能都是将数组的前一半数据移到后一半中: 【程序九】: '标准的移动数组的做法
Private Sub ShitArray(ab() As MyType)
Dim i As Long, n As Long
n = CLng(UBound(ab) / 2)
For i = 1 To n
Value(n + i) = Value(i)
Value(i).data = 0
Next
End Sub 【程序十】: '用指针的做法
Private Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" _
(ByVal dest As Long, ByVal source As Long, ByVal bytes As Long)
Private Declare Sub ZeroMemory Lib "kernel32" Alias "RtlZeroMemory" _
(ByVal dest As Long, ByVal numbytes As Long)
Private Declare Sub FillMemory Lib "kernel32" Alias "RtlFillMemory" _
(ByVal dest As Long, ByVal Length As Long, ByVal Fill As Byte) Private Sub ShitArrayByPtr(ab() As MyTpye)
Dim n As Long
n = CLng(UBound(ab) / 2)
Dim nLenth As Long
nLenth = Len(Value(1))
'DebugBreak
CopyMemory ByVal VarPtr(Value(1 + n)), ByVal VarPtr(Value(1)), n * nLenth
ZeroMemory ByVal VarPtr(Value(1)), n * nLenth
End Sub 当数组较大,移动操作较多(比如用数组实现HashTable)时程序十比程序九性能上要好得多。 程序十中又介绍两个在指针操作中会用到的API: ZeroMemory是用来将内存清零;FillMemory用同一个字节来填充内存。当然,这两个API的功能,也完全可以用CopyMemory来完成。象在C里一样,作为一个好习惯,在VB里我们也可以明确的用ZeroMemory来对数组进行初始化,用FillMemory在不立即使用的内存中填入怪值,这有利于调试。