Object pooling
BlitzMax Forums/BlitzMax Programming/Object pooling
| ||
Does anybody have a working example/framework code they would like to share? If it can also handle polymorphism that would be great. Thanks. |
| ||
An object pool is usually a simple container (list, stack etc.) containing your type. Since BlitzMax does not feature generics you might want to make a wrapper around the TList or similar so that you don't have to cast object-instances on insertion and removal. Then you just use it like this (peudo): function accuireObject() TObjectType obj if objPool is empty obj = new TObjectType else obj = objPool.last objPool.remove(obj) endif return obj endfunction function releaseObject(obj) if objPool.size >= MAX_POOL_SIZE then return objPool.insert(obj) endfunction Note:This is pseudo-code. Normally if you use the TList you'll loose the most obvious advantage of an object-pool because the internal adding of a link will usually be more or less as costly as "new <TType>". You might want it array-based with an algorithm that grows the array size starting @ some size and doubling the size each time it's required. |
| ||
I tried to implement something generic that I could implement in the base type but couldn't figure out so I ended up implementing a storage list, a create, an add and a remove(return to storage) function to each extended type with nothing other than a linked list stack. it works great except for the fact that I have to create very similar code to every type of object I create. I would like to see actual implementation of your code Mahan as that code is slightly over my head to implement. |
| ||
Thanks for the suggestions. I have an idea of my own, and I will share it if it works.. |
| ||
Any object pooling solution should use TList very carefully, as many operations generate a TLink object! A solution to reduce new object allocation that creates new objects probably won't work very well. |
| ||
. Last edited 2011 |
| ||
I wrote this in a hurry, and I've not used BlitzMax for a long while, so please check for any errors. Anyways, here is a very crude implementation: These are my timings: Normal GC (debug off): Creating 1000000 objects with normal memory management (1 alive at a time). took 105 ms. Creating 1000000 objects AT ONCE with normal memory management. took 1049 ms. Mallocing a workset of 1000 objects repeating 1000 times with normal memory management. took 167 ms. Working with a pool of 1000 objects with reusage 1000 times. took 70 ms. MultiThreaded (debug off): Creating 1000000 objects with normal memory management (1 alive at a time). took 132 ms. Creating 1000000 objects AT ONCE with normal memory management. took 242 ms. Mallocing a workset of 1000 objects repeating 1000 times with normal memory management. took 110 ms. Working with a pool of 1000 objects with reusage 1000 times. took 59 ms. |