Hacker Read top | best | new | newcomments | leaders | about | bookmarklet login

Malloc is O(n²) so it totally depend on how able you are to not do gradual allocation.


sort by: page size:

malloc isn't typically O(n) though, so I don't think that's reasonable math?

Afaik, a malloc is not guaranteed to return fast. With those requirements it's hard even in C.

malloc is a generic allocator, it needs to worry about a lot of things that are not common. A simple allocator will work most of the time, but the devil is in the details.

malloc() isn't O(1), but allocations in a normal GC are O(1).

There's a huge depth to a good malloc() implementation. While you're wise to avoid it when your interests are focused on kernel development, I'd recommend every programmer to have a go at writing malloc/free one day. Avoiding terrible performance problems is pretty tricky. At the very least, you'll gain a lot of respect for memory allocation and will discover that there's a lot of work going on behind the scenes when your code tries to allocate only a few bytes of memory.

Sure. But in general both malloc and cons are pretty zippy most of the time.

In most C libraries malloc() is O(log n), e.g. when implemented as balanced trees.

malloc isn't magic, just mmap some memory to dole out.

malloc already hands you more than you ask for in a lot of cases, check out malloc_usable_size.

Are you aware that malloc() is slow and doing all these tiny allocations is probably the biggest bottleneck in your program?

That would require implicit heap allocation, which is a lot to ask for in a language where malloc is a library function.

Malloc is at best a few hundred cycles, that's quite a lot of work if you can keep your data in L1. If you do a bit of work now you can save reallocs later.

Think bigger than changing the coefficient, there probably is no optimal factor.


My rule of thumb is to look at application's design and only ever use malloc where there is 1:N (or N:M) relationship between entities. Everything that's 1:1 should be allocated in a single step.

Malloc will still fail for overly large allocation sizes. If you try to malloc(-1), for example.

In such an environment, malloc() will do that.

The same thing can be said about malloc. It's a matter of degree, and different projects have (sometimes subtly) different requirements.

Any idea how much space overhead malloc has with entries as small as this? (<1 to 4> * 8 bytes)

Seems to me it could easily be a significant amount of overhead.


Yes as it turns out malloc is much faster if free doesn’t exist.

Really? One allocation every 50 to 100ms? That would mean you could only do 10 to 20 memory allocations per second. Now, I know that malloc is often very slow, but that seems unlikely.

Or do you mean 50 to 100 microseconds? That's still horrible, but I could believe it.

next

Legal | privacy