December 03, 2020, 08:52:49 PM

Author Topic: [bmx] Dynamic Arrays by AdamStrange [ 1+ years ago ]  (Read 514 times)

Offline BlitzBot

  • Jr. Member
  • **
  • Posts: 1
[bmx] Dynamic Arrays by AdamStrange [ 1+ years ago ]
« on: June 29, 2017, 12:28:41 AM »
Title : Dynamic Arrays
Author : AdamStrange
Posted : 1+ years ago

Description : how to manage automatic resizing arrays

Code :
Code: BlitzMax
  1. local myArraySize:int = 100
  2. local myArray:myType[myArraySize]
  3.  
  4. 'now to check and resize the array. the array is increased in steps of 50
  5. local newsize:int = 250
  6. While newsize => myArraySize
  7.         myArraySize :+ 50
  8.  
  9.         myArray = myArray[..myArraySize]
  10. Wend


Comments :


dna(Posted 1+ years ago)

 you could have used types to to the same thing.


Matty(Posted 1+ years ago)

 Hmm...so if the new size is greater by a value less than 50 elements...you still add 50 elements? seems a bit strange?


AdamStrange(Posted 1+ years ago)

 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


Guy Fawkes(Posted 1+ years ago)

 cool :)


ziggy(Posted 1+ years ago)

 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.


Yasha(Posted 1+ years ago)

 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.)


AdamStrange(Posted 1+ years ago)

 <div class="quote"> BlitzMax already allocates memory in chunks </div>That, i did not know :)


 

SimplePortal 2.3.6 © 2008-2014, SimplePortal