PDA

View Full Version : Array vs type optimization



MouseTrap
03-03-2009, 20:27
My company has PB/CC and i'm considering using it for project, but I haven't worked with PB before.
My question is about optimization of types vs arrays.
I created a type that is just an enumerated collection of LONGs but I can also just use an array of longs to achive the same thing.
I need the routines that work with this data to be as fast as possible.
Is there a performance difference if I use a UDT of longs rather than an array of longs?

Thanks

Petr Schreiber
03-03-2009, 21:07
Hi,

I am not sure what you mean by "enumerated collection of LONGs".
Could you post UDT definition here?


Petr

P.S. Which release of PB/CC it is?

MouseTrap
03-03-2009, 21:23
I am not sure what you mean by "enumerated collection of LONGs".
A UDT where where each field is a long variable...

Its ver.4

Petr Schreiber
03-03-2009, 21:33
So you are thinking whether it is better to use:


TYPE tEnum
l1 AS LONG
l2 AS LONG
l3 AS LONG
l4 AS LONG
END TYPE


or



DIM arr(3) AS LONG ' -- 0..3


If it is this, I would take pointer to array or UDT anyway, and then I would increase pointer by 4 bytes to go through ( LONG = 32bit ).

I think array would be more robust solution, you can REDIM it when you need.

You can also overlay array over UDT:


#COMPILE EXE
#DIM ALL

TYPE tEnum
l1 AS LONG
l2 AS LONG
l3 AS LONG
l4 AS LONG
END TYPE

FUNCTION PBMAIN () AS LONG

' -- 4 element array
DIM arr(3) AS LONG

' -- 4 element udt
DIM udtVar AS tEnum

' -- Virtual array over UDT :D
DIM arrayOverlay(3) AS LONG AT VARPTR(udtVar)

' -- Accessing l4 as it would be array
arrayOverlay(3) = 1024

' -- For real!
MSGBOX STR$(udtVar.l4)

END FUNCTION


While PB allows DIM arr(1 TO 4), it is recommended to use syntax I showed, as it results in faster indexing of array.
When you use pointers you are free to use any dim I presume.

I cannot give more advice, as optimization always depends from the task which needs to be done.


Petr

MouseTrap
03-03-2009, 21:35
Ok, That helps.
Thanks!

Petr Schreiber
03-03-2009, 21:40
Few general purpose hints:

- use register variables for FOR/NEXT loops


REGISTER i AS LONG

...

FOR i = 1 TO 1000000
...
NEXT


- use 32bit variables, prefer LONGs over DWORDs

- if you do not want to go pointer way, in case of complex structures inside structures it is advatageous to overlay simpler data structure ( DIM ... AT ) over the part you are interested in, as it results in less dereferencing, I guess


Petr

Michael Hartlef
04-03-2009, 11:05
Hi Petr,

interesting topic and the thing about REGISTER, well I didn't know that. Off to optimize some code tonight. :)

Michael