I have to manage a resource. It is basically a unique number to identify a Layer 2 connection in a switch. There can be 16k such connections and so every time a user wishes to configure a connection,he/she needs to allot a unique index. Similarly, when a user wishes to remove a connection, the resource (the number) must be released and must be available to configure(and identify) other connections. As of now i am using an bitmap based on unsigned char arrays to maintain which bit is set/unset
to monitor 16k numbers i am using an unsigned char array of 2048 bytes, wherein each bit represents a resource:
unsigned char bitmap_array[2048];
Is there a better way of doing the same, that does not involve suc开发者_JS百科h a huge chunk of static allocation?
another way could be using a Set [Hash/Tree], which size will be dynamically chosen. every element is in the set if and only if this resource is allocated.
the problems with these solution are:
1. it will be slower.
2. when number of elements is high, it will take more memory then the static array.
for 2k, I'd stick with the static bitmap array.
one more possibility:
using the same trick Virtual Memory uses (pages).
partition your 'array' into N parts, and create an extra table of size N.
every element in the table will be mapped a part of the array it is relevant to.
now, when you allocate resource k, you will have to allocate the part of the array which k is in, [and set all the other values to 0].
it will still be slower then the chunk, and when all entrees are allocated, it will requires extra N*4 bytes.
I'd use this solution only if the data is much larger then 2k.
more info: http://tldp.org/LDP/tlk/mm/memory.html
Is this embedded? 2k isn't that much memory by desktop standards. You could always use a hash-table, but you probably wont get the performance you are getting now. You can also just dynamically allocate the block if it makes you feel better.
My C might be a little garbled, but if I remember it should look like this:
unsigned char *ptr = (unsigned char *) malloc(2048 * sizeof (unsigned char));
//insert null pointer check here
Just remember to call free
when you are done...
Seriously, 2k of static allocation is probably fine.
精彩评论