Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

A common idiom that is no longer as common is to always create a stack buffer up to a certain small bound and then an allocation if it goes beyond:

   void dwim(unsigned count) {
     struct Something _buffer[10];
     struct Something* buffer;
     if (count < sizeof(_buffer) / sizeof(_buffer[0]))
       buffer = _buffer;
     else {
       buffer = (struct Something*) malloc(count * sizeof(struct Something));
     }
     doSomething(buffer, count);
     if (buffer != _buffer)
       free(buffer);
    }
It used to be really common to write that without considering if it was a necessary optimization or not - nowadays I would just malloc up front.


This pattern still exists in C++ in the form of custom containers that implement "small array optimization". The LLVM project is a heavy user of this pattern as far as I know and I have seen it in several proprietary codebases.


It's also used in std::string (small string optimization).


Same with Rust's smallvec crate.




Consider applying for YC's Winter 2026 batch! Applications are open till Nov 10

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: