Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Minimizing the amount of malloc() calls improves performance?

Tags:

c

malloc

Consider two applications: one (num. 1) that invokes malloc() many times, and the other (num. 2) that invokes malloc() few times. Both applications allocate the same amount of memory (assume 100MB).
For which application the next malloc() call will be faster, #1 or #2?
In other words: Does malloc() have an index of allocated locations in memory?

like image 369
Dor Avatar asked Jan 16 '10 22:01

Dor


People also ask

How can I make malloc faster?

The more often you call malloc, the more time it will take - so reducing the number of calls will give you a speed improvement (though whether it is significant will depend on your exact circumstances).

Is malloc and free slow?

The main reason why malloc() is rather slow is that it is providing a lot of functionality – the allocation of chunks of memory of variable size is somewhat complex.

What is the benefit of malloc?

malloc allocates a piece of memory as big as you ask it. It returns a pointer to the start of that memory, which could be treated similar to an array. If you write beyond the size of that memory, the result is undefined behavior. This means everything could work alright, or your computer may explode.

Does malloc increase heap size?

The first time, malloc creates a new space (the heap) for the program (by increasing the program break location).


1 Answers

You asked 2 questions:

  • for which application the next malloc() call will be faster, #1 or #2?
  • In other words: Does malloc() have an index of allocated locations in memory?

You've implied that they are the same question, but they are not. The answer to the latter question is YES.

As for which will be faster, it is impossible to say. It depends on the allocator algorithm, the machine state, the fragmentation in the current process, and so on.

Your idea is sound, though: you should think about how malloc usage will affect performance. There was once an app I wrote that used lots of little blobs of memory, each allocated with malloc(). It worked correctly but was slow. I replaced the many calls to malloc with just one, and then sliced up that large block within my app. It was much much faster.

I don't recommend this approach; it's just an illustration of the point that malloc usage can materially affect performance.

My advice is to measure it.

like image 188
Cheeso Avatar answered Oct 23 '22 08:10

Cheeso