I was implementing a circular buffer to store fixed-sized data structures like a queue. This circular buffer is initialized with three parameters:-
/*
* Initialize the ring buffer.
* @capacity Max capacity of ring buffer.
* @item_size Fixed size of item that will be put in this circular buffer.
* @item_cleaner Clean callback, NULL if cleanup not required.
*/
ringbuf*
ringbuf_create(size_t capacity, size_t item_size, clean_up_cb item_cleaner)
My circular buffer is always in wrapping
mode which means that last item is always replaced when new item is put in full circular buffer. Since, dynamically allocated objects can also be put into this buffer, therefore, circular buffer keeps reference a clean-up callback function to free up the items when they are replaced or deleted. But at the same time, this call back function can also be NULL
(when no clean up is required). Everywhere in my code, I've statements like these:-
if(buffer->callback != NULL)
buffer->callback(item);
Now, to prevent these if
statement, I put empty stub function when user does not provide any call back function. This prevent me to check every time if callback function is NULL
or not.
Using this approach, my code looks neat to me. But I'm not sure, which one of them is faster? On assembly level, how does empty function call
and if statement
relate in terms of speed? Are they equivalent?
Without worrying about speed, I'd probably just code:
if (buffer->callback) buffer->callback(item);
simply because it's clear and idiomatic as it is. And it'll certainly be no slower than a null function call.
An empty stub function is actually two JMP operations and allot of PUSH/POP operations on the CPU. An IF is usually a single COMP operation which is much cheaper than any JMP+PUSHS+POPS.
If your 'IF's usually return false/true then I won't worry about it as the CPU optimizes IFs in a very good way by predicting the result as long as the IFs are "predictable" (usually returns true or false or has some pattern of true/false)
I would go with the IFs.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With