Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which is faster: Empty Function Call or If Statements?

Tags:

performance

c

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?

like image 338
Shivam Avatar asked May 29 '12 10:05

Shivam


2 Answers

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.

like image 129
Michael Burr Avatar answered Oct 19 '22 23:10

Michael Burr


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.

like image 45
Gilad Avatar answered Oct 19 '22 23:10

Gilad