Tech Support > Computers & Technology > Programming > about vector
about vector
Posted by Karl St-jacques on July 25th, 2003


I'm new to programming, and I'm testing some things with vector. I wanted
to know what's faster between 2 choices...

My vector right now is 2d, 10 element by 20, so there's 200 elements
inside. I could easily access these element even if it was one dimension,
at the expense of some multiplication (i*10+j).

My Question is, what'is the most efficient one,
or does there's other alternative to this that i don't know about yet?

Thanks
Karl.
--
Using M2, Opera's revolutionary e-mail client: http://www.opera.com/m2/

Posted by David Turner on July 25th, 2003


Hello

"Karl St-jacques" <k.stjacques@videotron.ca> wrote in message
newsprsulryve3fmhkl@news.videotron.ca...
If your 2d array has "nice" dimensions, the compiler can usually optimize
the access into an expression like this:

lea ebx, [edi + 16*eax + 4*eax]

which is much faster than a multiplication. However, if you *really* need
to be certain that no multiplication will be involved, consider an array of
arrays:

typedef int* intvec;
intvec *db;

db = new intvec[20];
for(int i=0; i<20; ++i)
db[i] = new int[10];

With this type of structure, the compiler will generate the following code:

// db[3][4] = 0;
mov ebx, [ebx+12]
xor eax, eax
mov [ebx+16], eax

In other words, a multiplication and one lookup has been replaced by two
lookups. Of course, you have to remember to delete[] the array properly:

for(int i=0; i<20; ++i)
delete[] db[i];
delete[] db;

I hope this provides some insight.

Regards
David Turner



Posted by Alex on July 25th, 2003


On Fri, 25 Jul 2003 00:08:12 -0400, Karl St-jacques
<k.stjacques@videotron.ca> wrote:

It depends whether you're just pushing and popping the last element or
whether you're doing the same with elements in the middle or
beginning.


Alex
atheist #2007

Posted by Dan Tex1 on July 25th, 2003


From: Karl St-jacques k.stjacques@videotron.ca

To a degree ( possibly large ), it will depend partially on the language you
are using.

By example, Fortran has built in support for multi-dimensional arrays.
Therefore, it is reasonable to assume that any Fortran compiler ( that isn't a
total piece of crap ) would give you faster access using a 2D array. Yes...
I think that most compilers really Should be able to access elements of a 1D
array faster than those in a 2D array. However, if your code has to execute
multiplications, etc. to figure out which element to access from the 1D array
first, things are going to slow down. In Fortran, and I'd assume, probably
any language that has built in support for multi-dim arrays... I'd vote that
the 2D option is likely faster.

In languages that don't have straight forward multi-dim arrays, I'm sure there
are other considerations that will affect things.

Dan :-)


Similar Posts