This code has been declared by its author to be Public Domain code.
Download source code | Dynamic Arrays by AdamStrange | 2015 |
| |
|
how to manage automatic resizing arrays |
local myArraySize:int = 100
local myArray:myType[myArraySize]
'now to check and resize the array. the array is increased in steps of 50
local newsize:int = 250
While newsize => myArraySize
myArraySize :+ 50
myArray = myArray[..myArraySize]
Wend |
Comments |
you could have used types to to the same thing.
|
|
Hmm...so if the new size is greater by a value less than 50 elements...you still add 50 elements? seems a bit strange?
|
|
i just used 50 as a guide. The amount you increase is up to you. :) I am dealing with something that could increase by lots or a little, so instead of predefining a large array (and not using it) this was a good way (i'm dealing with 100's of items)
the reason for not using types, is referencing. I need to be able to reference any item at any time instantly
|
|
Beware that resizing an array is a very expensive operation CPU wise.If you need to add lots of elements, it's faster to convert the array to a linkedlist, add elements, and convert it back to an array.
|
|
The conventional approach with dynamic arrays is to double, or otherwise multiply, the capacity on resize, rather than adding to it. That way, the more you add elements, the less likely it is that an extension will be necessary in future.
To combat wastefulness, you can combine the strategy with a ShrinkToFit method for use once you're done adding items.
That said, ziggy is right: if you know you're going to be adding a dynamic number of elements to a collection, start with a linked list. Arrays should really either be fixed-size, or only resized in places where performance doesn't matter.
(That said ^2, BlitzMax already allocates memory in chunks, so resizing an array by one or two elements may well be free, if the existing memory block is already big enough for it. The same goes for Blitz3D and banks. Haven't checked the specific details though.)
|
|
BlitzMax already allocates memory in chunks
That, i did not know :)
|
Code Archives Forum