tags:

views:

32

answers:

1

When using a Visual Basic two-dimensional array, which index varies fastest? In other words, when filling in an array, should I write...

For i = 1 To 30
    For j = 1 To 30
        myarray (i,j) = something
    Next
Next

or

For i = 1 To 30
    For j = 1 To 30
        myarray (j, i) = something
    Next
Next

(or alternatively does it make very much difference)?

+2  A: 

Column major. VB6 uses COM SAFEARRAYs and lays them out in column-major order. The fastest access is like this (although it won't matter if you only have 30x30 elements).

For i = 1 To 30 
    For j = 1 To 30 
        myarray (j, i) = something 
    Next 
Next 

If you really want to speed up your array processing, consider the tips in Advanced Visual Basic by Matt Curland, which shows you how to poke around inside the underlying SAFEARRAY structures.

For instance accessing a 2D SAFEARRAY is considerably slower than accessing a 1D SAFEARRAY, so in order to set all array entries to the same value it is quicker to bypass VB6's SAFEARRAY descriptor and temporarily make one of your own. Page 33.

You should also consider turning on "Remove array bounds checks" in the project properties compile options.

MarkJ