alephzero icon indicating copy to clipboard operation
alephzero copied to clipboard

Is there going to be multiple memory copies when Packet is constructed using std::string?

Open gppyls opened this issue 1 year ago • 4 comments

https://github.com/alephzero/alephzero/blob/6f81ec985724bad87b04fba44e2a664f272f67a7/src/packet.cpp#L85

The reason why the parameter of the constructor Packet::Packet(std::string payload) doesn't use const & or &&, and uses value passing, even if moving is performed, copying will still occur.

gppyls avatar May 05 '24 11:05 gppyls

This is standard c++ best practice for accepting a string which needs to be retained. This does the minimum copies necessary. If you pass an lvalue, one copy will be made. If you pass an rvalue, such as with std::move, no copies are performed. It is worse to enumerate constructors for const& and &&. Those will not cover all the cases.

lshamis avatar May 05 '24 16:05 lshamis

Might be worth looking at https://clang.llvm.org/extra/clang-tidy/checks/modernize/pass-by-value.html

lshamis avatar May 05 '24 16:05 lshamis

Yes, I used a shorter string length when doing the test, and the compiler was optimized for SSO, so the addresses of several intermediate variables I tested were different

gppyls avatar May 06 '24 05:05 gppyls

Small-String-Optimization involves storing short strings directly within the string object, rather than a pointer to heap memory. They cannot be effectively moved, and Packet needs to guarantee the lifetime of the string. Thank you for sharing your findings, but the issue tracker here isn't the right place for learning C++. If you have specific questions about alephzero's functionalities, feel free to reach out.

lshamis avatar May 06 '24 16:05 lshamis