This question got rather a freezing reception at SO, so I decided to delete it there and try here instead. If you think it does not fit here either, please at least leave a comment on suggestion how to find an example I'm after...
Can you give an example, where using C99 VLAs offers a real advantage over something like current standard heap-using C++ RAII mechanisms?
The example I am after should:
- Achieve an easily measurable (10% maybe) performance advantage over using heap.
- Not have a good workaround, which would not need the whole array at all.
- Actually benefit from using dynamic size, instead of fixed maximum size.
- Be unlikely to cause stack overflow in normal use scenario.
- Be strong enough to tempt a developer needing the performance to include a C99 source file in a C++ project.
Adding some clarification on the context: I mean VLA as meant by C99 and not included in standard C++: int array[n]
where n
is a variable. And I am after an example of use case where it trumps the alternatives offered by other standards (C90, C++11):
int array[MAXSIZE]; // C stack array with compile time constant size
int *array = calloc(n, sizeof int); // C heap array with manual free
int *array = new int[n]; // C++ heap array with manual delete
std::unique_ptr<int[]> array(new int[n]); // C++ heap array with RAII
std::vector<int> array(n); // STL container with preallocated size
Some ideas:
- Functions taking varargs, which naturally limits item count to something reasonable, yet is without any useful API-level upper limit.
- Recursive functions, where wasted stack is undesirable
- Many small allocations and releases, where heap overhead would be bad.
- Handling multi-dimensional arrays (like arbitrarily sized matrices), where performance is critical, and small functions are expected to get inlined a lot.
- From comment: concurrent algorithm, where heap allocation has synchronization overhead.
Wikipedia has an an example which does not fulfill my criteria, because the practical difference to using heap seems irrelevant at least without context. It is also non-ideal, because without more context, it seems item count could very well cause stack overflow.
Note: I'm specifically after an example code, or suggestion of an algorithm which would benefit from this, for me to implement the example myself.
alloca()
would really outshinemalloc()
in a multithreaded environment because of the lock contention in the latter. But this is a real stretch since small arrays should just use a fixed size, and large arrays will probably need the heap anyway.alloca
, which I think are basically same thing). But that multithreaded thing is good, editing question to include it!malloc
behavior conforms to the C standard.