Can I change array size dynamically?
BlitzMax Forums/BlitzMax Beginners Area/Can I change array size dynamically?
| ||
I want to use arrays for my program so i can use the index to access each variable quickly, but i also want the array size to grow as and when i need it. The nature of my program means i have to store a large number of arrays but the array could be very small or very large. I have no idea which before the program starts. My question is can i change array size as and when i want in Blitz or is it fixed? |
| ||
You can resize arrays. It's called "array slicing"..Local a:Int[10] For i:Int = 0 To 9 a[i] = i Next For i:Int = EachIn a Print i Next Print "---" ' resize up... a = a[..20] For i:Int = 10 To 19 a[i] = i Next For i:Int = EachIn a Print i Next Print "---" ' resize down a = a[5..9] For i:Int = EachIn a Print i Next Print "---" |
| ||
Just keep in mind this isn't a magically efficient solution to a notoriously hard problem. Your original array doesn't actually change size. BlitzMax is allocating a new array and copying values from the old array, which is then discarded and later garbage collected |
| ||
another thing to note is that arrays are objects so it would be as slow as variables objects. if you want to access values fast use pointers. |
| ||
If you're dynamically adding and remomoving objects, it is several orders of magnitud faster to use lists. Arrays: -very slow resizing, but very fast item indexing Lists: -very fast adding and removing items, but slow indexing of items If you typically access items in a sequential way, using For Each in a List is usually fast enough, so unless you're accesing all the time random indexes on the data structure, linked lists are usually better. there there are maps, that do provide a faster way to add and remove items than resizing arrays, but slower than lists, and it allows indexed access to container items, faster tha lists, but slower than arrays. |
| ||
Don't forget about TMap! |
| ||
If you don't need the old values when resizing the array, you can just assign a new array instead of using slices.Local a:Int[10] Print a.length a = New Int[30] Print a.length |
| ||
Ok thanks very much for all the help. I like that you can resize arrays. I probably could use that because my program doesnt have to be that fast or efficient in any way. I might have a go using lists first to see if i can make that work though. Thanks again :) |