4 ms·
IIRC faster, because variable-length arrays in c99 just bump down the stack pointer, while malloc can be pretty expensive. But a single malloc is nothing compa
by alexgartrell 15y ago
IIRC faster, because variable-length arrays in c99 just bump down the stack pointer, while malloc can be pretty expensive.
But a single malloc is nothing compared to the cost of a context switch into kernel mode.
- apaprocki 15y agoYou can simply use alloca() as a replacement for malloc() to avoid depending on VLA support.
- cpeterso 15y agoOr just declare a large static buffer.
- tedunangst 15y ago"Nobody will ever echo this much data!"
- GreySyntax 15y agoOh wait they will
- tmp43522 15y agoIt's actually not a bad suggestion #define BUF_INITIAL 1024 char buf[BUF_INITIAL]; int main(int argc, char** argv) { char* p; ... p = len > BUF_INITIAL ? malloc(len) : buf; ... write(1, p, len); ... }
- cpeterso 15y agodjb's allocator alloc() does this. He preallocates a 4 KB static buffer before hitting system malloc(). Avoiding the overhead of malloc() is pretty important for the performance of systems like qmail that fork many small processes.
- sliverstorm 15y agoMany small processes? How many? 4 KB * (many) could be frightening.
- jff 15y agoIf your system has 32,000 processes and you allocate 4 KB to each of them... that's 128 MB. I'm not crapping my pants at that figure because even the oldest machine in my office, an old Thinkpad, has 2 GB of RAM.
- tedunangst 15y agoThat's ridiculous. The overhead of fork is about a bajillion times higher than malloc.
- aidenn0 15y agoAre you sure? I'd bet it's greater, I'd not bet that it's an order of magnitude better, fork() has been optimized a lot more than brk().
- adestefan 15y agoWith a COW fork() I bet it's smaller. I smell a test coming on, but alas it's late here and I'm going to bed. I'm also guessing that 4k was chosen because a malloc() of 1 page is faster than a malloc() of >1 page. Of course that's with the assumption that the systems use a 4k page size.
- tedunangst 15y agoalloca sucks. The error handling is "haha, you overflowed your stack." (VLA sucks for the same reason.)