4 ms·
I am curious to know why every single in function parameters in this project are passed by value. Too much RAM left unused in our modern desktops?
by random9e7de4c1 5y ago
I am curious to know why every single in function parameters in this project are passed by value. Too much RAM left unused in our modern desktops?
- stockerta 5y agoIn the world of electron applications eating ram like nothing, this pales in comparison.
- benibela 5y agoThere is a good chance that electron comes with a highly optimized JSON parser that is vastly faster the one in the article
- pkolaczk 5y agoWhy do you think pass-by-value takes up more memory? The data gets packed on the stack pretty densely, so as long as the data structures are tiny, that shouldn't be a problem. On the flip side heap allocation is typically prone to some level of fragmentation, which actually does waste memory.
- random9e7de4c1 5y agoI agree with your point for small size data structures. But in general, and in the case of the OP source code, he doesn't even need to copy its arguments to pass them by value, he should pass them via a const reference, and just pass the address.
- spacechild1 5y agoPassing by value can fine, but then the author should use std::move when passing it on to other functions. But you are right that passing by (const) reference is standard practice and less error prone.
- random9e7de4c1 5y agoPassing by value can be fine for small size structs, but it is not the common practice. I expected to see any of this function to use const reference. For general guidelines on parameters passing (and other guideilines), the C++ core guidelines are pretty useful for those who want to learn: https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Rf-conventional https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines...
- spacechild1 5y ago> Passing by value can be fine for small size structs, but it is not the common practice. It can also be fine with larger objects (with heap memory) if you plan to make a copy anyway, because you can just use std::move. The advantage is that the function works the same with lvalue and rvalue references, so you don't have to write the same function twice. An alternative is to use "universal references" (T&& where T is a template parameter) + std::forward. This is often seen in constructors. But yeah, usually you would just use const references. BTW, instead of 'const std::string&' it is even better to use a std::string_view because it works both with std::string and C strings - without creating hidden copies for the latter. If you pass a C string as a 'const std::string&' argument, you actually create a new temporary std::string, whereas std::string_view will just store the pointer and length.