I am implementing an order book in c++. I'm modelling it after this implementation which has won awards for speed.
The reason it is fast is explained as using static arrays so that the entire order book is allocated on the stack instead of the heap.
What surprised me is that there is a significant performance gain from initializing the arrays with bzero. Below is init
function in the linked c implementation. Commenting out the bzero
calls results in roughly 2-3x slower performance when I fed it sample data and measured the results.
void init() {
/* Initialize the price point array */
bzero(pricePoints, (MAX_PRICE + 1) * sizeof(pricePoint_t));
/* Initialize the memory arena */
bzero(arenaBookEntries, MAX_NUM_ORDERS * sizeof(orderBookEntry_t));
...
}
In my C++ code, my static arrays were written like below. I was under the impression in C++ 11 that setting an array = {}
would initialize it with zero values. Hence I didn't think I would need to use bzero
. Testing against sample data indicated my implementation was equivalent to the c implementation without bzero
. Adding the bzero
call to the constructor of my OrderBook
class, resulted in performance equivalent to the C implementation.
So my question is why did using bzero
result in faster performance?
// header file
OrderBook {
static PricePoint _price_points[MAX_PRICE / TICK_SIZE];
static Order _orders[MAX_ORDERS];
}
//cpp file
PricePoint OrderBook::_price_points[MAX_PRICE / TICK_SIZE] = {}
Order OrderBook::_orders[MAX_ORDERS] = {};