free_list 0.1.0 free_list: ^0.1.0 copied to clipboard
A free list implementation. Good for effecient reuse of reusable objects that have a high overhead to initialize
Free List #
A free list implementation. Good for effecient reuse of reusable objects that have a high overhead to initialize.
Example #
import 'package:free_list/free_list.dart';
main() {
// Create a free list of strings (lame example) with a max size of 3
var freeList = new FreeList<String>.max(() {
return "super expensive resource";
}, 3);
// Acquire 3 resources from the free list
var res1 = freeList.acquire();
var res2 = freeList.acquire();
var res3 = freeList.acquire();
print('res1 ${res1}');
print('res2 ${res2}');
print('res3 ${res3}');
print('current size ${freeList.size}');
// Restore the 3 resources to the free list
freeList.release(res1);
freeList.release(res2);
freeList.release(res3);
print('current size ${freeList.size}');
// Acquire 4 resources from the free list
var res4 = freeList.acquire();
var res5 = freeList.acquire();
var res6 = freeList.acquire();
var res7 = freeList.acquire();
print('res4 ${res4}');
print('res5 ${res5}');
print('res6 ${res6}');
print('res7 ${res7}');
print('current size ${freeList.size}');
// Restore the 4 resources to the free list
freeList.release(res4);
freeList.release(res5);
freeList.release(res6);
freeList.release(res7);
print('current size ${freeList.size}');
}
Public Interface #
library free_list;
import 'dart:collection';
class FreeList<T> {
/**
* The free list constructor which takes a closure constuctor
* responsible for allocating objects for the free list
*
* @param {T()} constructor - The closure constructor
*/
FreeList(T constructor());
/**
* A specialization of the constructor where you can manually
* specify the maximum size of the free list
*
* @param {T()} constructor - The closure constructor
* @param {int} max - The max size of the free list
*/
FreeList.max(T constructor(), int max);
/**
* If there are available resources in the free list, returns the
* hottest one, otherwise allocate and return a new one.
*
* @return {T} - An instance of the allocated type
*/
T acquire();
/**
* Add a no longer used resource to the free list to be used by
* another computation
*
* @param {T} value - The value to return to the free list
* @return {void}
*/
void release(T value);
/**
* The current size of the free list
*
* @return {int} - Size
*/
int get size => this._currentSize;
/**
* The max size of the free list
*
* @return {int} - Max size
*/
int get maxSize => this._maxSize;
}