potrzebie
potrzebie

Reputation: 1798

Allocate a large block instead of many small?

I'm reading a 2 MB word list with about 200 000 words into memory. To be able to index them I use a char * array. Since the words won't grow or shrink, is it better to read the whole file into one memory block and let the pointers point into that, rather than doing a malloc() for every word?

Upvotes: 1

Views: 257

Answers (1)

John Zwinck
John Zwinck

Reputation: 249223

Contrary to some of the comments posted so far, if you are tight on memory, you should allocate a single large block. This is because each malloc() you do has some overhead which is more or less fixed. This overhead will be a few bytes per allocation, so many small allocations could have you losing half your memory to overhead.

If you care a lot about performance (speed), you should also use a single allocation. It will improve locality and cache utilization, and reduce the number of system calls during startup and also teardown.

Upvotes: 5

Related Questions