6 ms·
For large allocations, realloc can remap virtual memory instead of doing a naive copy: http://blog.httrack.com/blog/2014/04/05/a-story-of-realloc-and-laziness/
by acconsta 11y ago
For large allocations, realloc can remap virtual memory instead of doing a naive copy:
http://blog.httrack.com/blog/2014/04/05/a-story-of-realloc-and-laziness/ http://blog.httrack.com/blog/2014/04/05/a-story-of-realloc-a...
- acqq 11y agoThat's exactly when I'd use realloc. Looking who wrote the text, I also respect cperciva and believe he must have some good reasons and I'd be glad read which use cases he had, more than just "what's wrong with different reallocs." Because I'm not surprised that the corner cases aren't to everybody's (or even anybody's) satisfaction. It's C. Less is more and all that.
- cperciva 11y agoAnd for small allocations, realloc can expand or shrink an allocation in-place, because it knows where it is placing other memory allocations.
- acqq 11y agoYes. If the allocation block is 16 bytes for example, the string growing from 10 to 11, 12, 13 etc could still be on the same place. But in which use cases are frequent reallocs actually needed, so much that you can recognize the performance impact? I'd really like to know, as I personally never had such problems. When the single allocations were too expensive I've just used some kind of memory pool. For small stuff realloc is still more expensive than just a few instructions on average when some pool is used.
- cperciva 11y agoThe classic example of frequent reallocs is this perl code: $x .= $_ while (<>); I believe this has been fixed now, but perl used to realloc for each append operation, which resulted in O(N^2) time complexity if realloc didn't operate in-place.
- acqq 11y agoBut I wouldn't expect of you to assume that a "every time realloc" should be an optimal and at the same time a portable solution in such a case?
- cperciva 11y agoNo, I don't. If you look at the code in question, every time I expand an allocation I at least double it.
- acqq 11y agoI'd expect that such growth seldom allows the realloc to remain in-place (unless it's the last thing allocated before and already in a big preallocated chunk of the allocator)? Have you observed what you then get in your program? Which allocator is used underneath?
- cperciva 11y agoI haven't looked. I use whatever allocator is in libc anyway, so it will depend on what platform you're running on. At worst, using realloc produces the same results as malloc/memcpy/free. At best, it might save a memcpy. No harm in giving it that flexibility.