What is faster: empty function or message call?

I used a circular buffer to store fixed-size data structures such as 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 the last element is always replaced when a new element is placed in a full circular buffer. Since dynamically allocated objects can also be placed in this buffer, the circular buffer therefore saves a reference to the cleanup callback function to free the elements when they are replaced or deleted. But at the same time, this callback function can also be NULL (unless cleanup is required). Everywhere in my code I have statements like this: -

 if(buffer->callback != NULL) buffer->callback(item); 

Now, to prevent this if , I put an empty stub function when the user does not provide any callback function. This prevents me from checking every time if the callback function is NULL or not.

Using this approach, my code looks neat to me. But I'm not sure which one is faster? At the assembly level, how do empty function call and if statement relate in terms of speed? Are they equivalent?

+6
source share
2 answers

The empty stub function is actually two JMP operations and allocation of PUSH / POP operations on the CPU. IF is usually a single COMP operation, which is much cheaper than any JMP + PUSHS + POPS.

If your IF usually returns false / true, I wonโ€™t worry about that since the CPU optimizes IFs in a very good way, predicting the result while the IFs are โ€œpredictableโ€ (usually returns true or false or has some true / false pattern)

I would go with IFs.

+2
source

Without worrying about speed, I would probably just code:

  if (buffer->callback) buffer->callback(item); 

simply because it is clear and idiomatic as it is. And this, of course, will not be slower than calling a null function.

+3
source

Source: https://habr.com/ru/post/916899/


All Articles