3 ms·
Actually, I got curious and tried it out. Turns out Rust didn't optimize the heap case: it used the caller's stack, and only then copied the value to the heap.
by mkishi 12y ago
Actually, I got curious and tried it out. Turns out Rust didn't optimize the heap case: it used the caller's stack, and only then copied the value to the heap.
https://play.rust-lang.org/?code=%23!%5Bfeature(core)%5D%0A%0A%23%5Bderive(Debug)%5D%0Astruct%20BigStruct%20%7B%0A%20%20%20%20a%3A%20i64%2C%0A%20%20%20%20b%3A%20i64%2C%0A%20%20%20%20c%3A%20i64%2C%0A%7D%0A%0Afn%20main()%20%7B%0A%20%20%20%20let%20a%20%3D%20Box%3A%3Anew(test())%3B%0A%20%20%20%20println!(%22%7B%3A%3F%7D%22%2C%20a)%0A%7D%0A%0A%23%5Binline(never)%5D%0Afn%20test()%20-%3E%20BigStruct%20%7B%0A%20%20%20%20BigStruct%20%7B%20a%3A%2011111%2C%20b%3A%2022222%2C%20c%3A%2033333%20%7D%0A%7D https://play.rust-lang.org/?code=%23!%5Bfeature(core)%5D%0A%...
- pcwalton 12y agoBecause it would change the semantics of the program. Where heap allocations happen is considered a side effect, and forcing a function to be inline(never) also makes it have unconstrained side effects (in some cases). Those side effects cannot be reordered.
- steveklabnik 12y agoThat's because of `Box::new`, I'd think. If you use the box keyword, you should get the placement new effect.
- mkishi 12y agoThank you! I thought the box keyword was simply a syntactic sugar -- I'm not that familiar with placement new, even in C++. Note for the interested: the optimization works right now, even though the keyword is behind the box_syntax feature gate. Updated test: https://play.rust-lang.org/?code=%23!%5Bfeature(core)%5D%0A%23!%5Bfeature(box_syntax)%5D%0A%0A%23%5Bderive(Debug)%5D%0Astruct%20BigStruct%20%7B%0A%20%20%20%20a%3A%20i64%2C%0A%20%20%20%20b%3A%20i64%2C%0A%20%20%20%20c%3A%20i64%2C%0A%7D%0A%0Afn%20main()%20%7B%0A%20%20%20%20let%20a%20%3D%20box%20test()%3B%0A%20%20%20%20println!(%22%7B%3A%3F%7D%22%2C%20a)%0A%7D%0A%0A%23%5Binline(never)%5D%0Afn%20test()%20-%3E%20BigStruct%20%7B%0A%20%20%20%20BigStruct%20%7B%20a%3A%2011111%2C%20b%3A%2022222%2C%20c%3A%2033333%20%7D%0A%7D https://play.rust-lang.org/?code=%23!%5Bfeature(core)%5D%0A%...