4 ms·
question: which is cheaper, stack object allocation/creation or object pooling, in languages like C/C++/Rust?
by wangii 11y ago
question:
which is cheaper, stack object allocation/creation or object pooling, in languages like C/C++/Rust?
- pcwalton 11y agoGenerally the stack, because the cache behavior is better and you can allocate an entire activation record at one time. The compiler is also often able to optimize the allocations better, for example by promoting stack objects to registers.
- vitalyd 11y agoFor the most part stack allocs would be faster unless ctor does something ridiculously expensive. Also, one typically doesn't pool objects that are confined to the current thread's execution - it's mostly for heap references that outlive requests/transactions/etc.
- jacquesm 11y agoStack for sure. But if you want any kind of persistence then stack is right out and an object pool would be faster.
- tbirdz 11y agoThe stack is cheaper, but it is a limited size. If you need more objects than would fit on the stack, pooling might be a better choice.
- joelwilliamson 11y agoThe stack doesn't have to be limited. On a 64-bit system, you can give each thread a couple of terabytes of stack space with no problem.
- aidenn0 11y agoFor amd64 on linux you only have 128TB; with green threads I regularly use a lot more than 64 threads.