3 ms·
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 dwi
by cancerhacker 4y ago
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.
- gmueckl 4y agoThis 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.
- alpaca128 4y agoSame with Rust's smallvec crate.
- spacechild1 4y agoIt's also used in std::string (small string optimization).