3 ms·
Can't you just initialize everything at once before you need it rather than initializing one object here and there?
by PyroLagus 7y ago
Can't you just initialize everything at once before you need it rather than initializing one object here and there?
- skohan 7y agoIt depends heavily on the problem domain. In some cases this is possible, but it's often the case that you will not know what resources you will need at the beginning of execution. Also the implementation of "initialize everything at once" in an RIAA paradigm is not necessarily going to be the most efficient possible implementation. For instance, I might want to do something like this (in a made-up language): struct A { ... } func init() { let a1 = new A(); let a2 = new A(); let a3 = new A(); } The most efficient way to implement this would be to allocate enough memory to store a1, a2, and a3 and then run the initialization method 3 times over that memory. But it's likely that instead the compiler will allocate a1, initialize a1 and so on with a2 and a3. Since the allocations are separate, maybe another thread takes precedence between the allocation of a2 and a3 and allocates some memory, so these values are not contiguous in memory, and I get worse caching performance when accessing them. In this toy example with 3 values it doesn't make aa lot of difference, but if you add up all these marginal costs in a large application it absolutely does cost a lot of performance.
- 0815test 7y ago> The most efficient way to implement this would be to allocate enough memory to store a1, a2, and a3 and then run the initialization method 3 times over that memory. Only if a1, a2, a3 are also freed at once. In which case, you can just put all three in a struct that is allocated as a single block. Rust doesn't yet support this very well in the general case, because its support for what C++ calls "placement new" and customized allocation in general is not complete or stabilized. But doing this in a more hackish special-cased way is already possible in many cases.
- skohan 7y ago> Only if a1, a2, a3 are also freed at once. Yes exactly. This is meant to be illustrative of the case suggested in the parent comment, where all required runtime objects are known and can be initialized together at the beginning of execution. edit: it may be possible to program around some of the worst performance pitfalls of RAII in many cases, but you will end up with very non-idiomatic code, which I would take as evidence that RAII is not ideal for memory performance.