4 ms·
Curious to know why `drop` isn't called automatically by the compiler as soon as possible (since the type system already seems to know it is safe). Is there a
by hrjet 12y ago
Curious to know why `drop` isn't called automatically by the compiler as soon as possible (since the type system already seems to know it is safe).
Is there a trade-off involved here?
- kibwen 12y agoFreeing resources as soon as humanly (computerly?) possible will optimize your memory usage, but can actually be worse for execution speed. If you're willing to use slightly more memory, it's generally faster to free memory in coarse chunks than one-thing-at-a-time. So even though Rust can conceivably free memory sooner, it might as well defer freeing until the end of the scope, since it can prove that that's safe. To take this to the logical extreme, see this awesome post from Walter Bright, where he doubles the speed of the D compiler by providing a custom malloc implementation that never frees, leaking all memory until the end of the process: http://www.drdobbs.com/cpp/increasing-compiler-speed-by-over-75/240158941 http://www.drdobbs.com/cpp/increasing-compiler-speed-by-over...
- hrjet 12y agoThanks. I can see the pro in that choice. But the con would be memory starvation (assuming that heap is bounded as in the JVM). I think one middle-path could be to mark the resource as released as soon as compiler detects it, and then release it 1. when the allocator is starved or 2. when the resource goes out of scope 3. when drop() is explicitly called
- kibwen 12y agoHeaps aren't bounded in systems contexts; a process is free to gobble up the entire address space if left unchecked, which would (hopefully) result in your process being killed by the OS. I believe we have discussed your first bullet point there, with regard to attempting to free waiting-for-the-scope-to-end-but-not-being-used memory in the event that allocation fails. But this is a hairy subject, and is beyond my expertise. Note that your third bullet point does cause memory to be freed immediately, because the `drop` function is a scope all its own.
- ben0x539 12y agoOne reason is probably emulating the way RAII works in C++, and allowing "low level" code to use idioms like { let _lock = acquire_lock(); use_resource(); } // lock is released here, whether use_resource() returned or caused stack unwinding
- hrjet 12y agoMakes a lot of sense: reduces generated code duplication. Just needs one "release" block per scope.