Home
Search
 
What's New
Index
Books
Links
Q & A
Newsletter
Banners
 
Feedback
Tip Jar
 
XML RSS Feed
 
 
 
 
 
 
 
 
Old Pages
 
Old Index
Site Map
What's New
 
Books
How To
Tips & Tricks
Tutorials
Stories
Performance
Essays
Links
Q & A
New in VB6
Free Stuff
Pictures
 
 
 
TitleCopy memory extremely quickly
KeywordsRtlMoveMemory, copy memory, MemCopy, CopyMemory, array, memory
CategoriesTips and Tricks, Miscellany, Software Engineering
 
When you click the Build Array button, the program makes two arrays containing Longs of a specified size. When you click the For Loop button, the program copies the values from one array to the other using a For loop.

When you click Assignment, the program sets Array2 = Array1. This doesn't work in versions of VB before VB 6 and won't work for copying only part of the array but it is fast and easy.

When you click MemCopy, the program uses the RtlMoveMemory API function, which is typically much faster. In one test using an 8MB array, the program took 0.66 seconds using a For loop, 0.17 seconds using assignment, and only 0.06 seconds using RtlMoveMemory. (All of these are pretty fast!)

 
' Declare the memory copying funciton.
Private Declare Sub CopyMemory Lib "kernel32" Alias _
    "RtlMoveMemory" (Destination As Any, Source As Any, _
    ByVal Length As Long)

Private Array1() As Long
Private Array2() As Long
Private NumItems As Long
Private Bytes As Single

Private Sub CmdBuildArray_Click()
    MousePointer = vbHourglass
    TimeLabel.Caption = ""
    DoEvents
    
    Bytes = CSng(SizeText.Text) * 1024 * 1024
    NumItems = Bytes / Len(NumItems)
    ReDim Array1(1 To NumItems)
    ReDim Array2(1 To NumItems)

    CmdForLoop.Enabled = True
    CmdMemCopy.Enabled = True
    MousePointer = vbDefault
End Sub

Private Sub CmdForLoop_Click()
Dim start_time As Single
Dim i As Long

    MousePointer = vbHourglass
    DoEvents
    
    start_time = Timer
    For i = 1 To NumItems
        Array2(i) = Array1(i)
    Next i
    TimeLabel.Caption = _
        Format$(Timer - start_time, "0.00")
    MousePointer = vbDefault
End Sub

Private Sub cmdAssignment_Click()
Dim start_time As Single
Dim i As Long

    MousePointer = vbHourglass
    DoEvents
    
    start_time = Timer
    Array2 = Array1
    TimeLabel.Caption = _
        Format$(Timer - start_time, "0.00")
    MousePointer = vbDefault
End Sub

Private Sub CmdMemCopy_Click()
Dim start_time As Single

    MousePointer = vbHourglass
    DoEvents
    
    start_time = Timer
    MemCopy Array2(1), Array1(1), Bytes
    TimeLabel.Caption = _
        Format$(Timer - start_time, "0.00")
    MousePointer = vbDefault
End Sub

Private Sub SizeText_Change()
    TimeLabel.Caption = ""
    CmdForLoop.Enabled = False
    CmdMemCopy.Enabled = False
End Sub
 
In 16-bit environments, use hmemcpy instead of RtlMoveMemory.
 
 
Copyright © 1997-2003 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated