1

I checked this question, and most answers say that I should pass it by value despite it's clearly passing more data (since by value you pass 8 bytes while by reference only 4 bytes, in 32bit system sizeof(string_view) > sizeof(string_view*)) is that still relevant in C++20/17 ? and can someone explains why exactly ?

0xDEADC0DE
  • 323
  • 3
  • 12
  • *while by reference only 4 bytes* -- Where did you get this information from? – PaulMcKenzie Oct 05 '20 at 18:18
  • 1
    I think refrence has an overhead in general. Thats why you do not pass ints by ref, right? – User12547645 Oct 05 '20 at 18:18
  • @0xDEADC0DE Internally passing by reference is implemented as passing by pointer. So within the function you need always to dereference the pointer. – Vlad from Moscow Oct 05 '20 at 18:22
  • https://stackoverflow.com/questions/27256377/c-view-types-pass-by-const-or-by-value This explains your question in detail. – Computeshorts Oct 05 '20 at 18:23
  • 2
    References may incur additional overhead, and often (but not necessarily!) is implemented as pass-by-pointer. In one performance experiment, references cut our performance by an order of magnitude, but that was pathologically bad for references. Our cutoff for parameters was 256 bytes for parameters or less is as-or-more performance efficient, and 512 bytes or larger was better as a reference. 256-512 was a bit of a grey zone. That's for a particular platform, and other platforms will certainly have different behavioral characteristics. (`-O3` and profile, profile, profile.) – Eljay Oct 05 '20 at 18:24
  • @Eljay That's what I needed to know, is the 256 bytes cutoff in 32bit or 64bit systems ? – 0xDEADC0DE Oct 05 '20 at 18:27
  • 1
    For our app, it is on two different-but-closely-similar 64-bit platforms. We're porting our app to two more 64-bit platforms of different architectures, which will invalidate our previous testing and we'll have to do it all over again. Change is the only constant. Software engineering is never having to say *you're done*. – Eljay Oct 05 '20 at 18:29

1 Answers1

4

Indirection through a reference (as well as a pointer) has a cost. That cost can be more than the cost of copying a few bytes. As in most cases, you need to verify through measurement whether that is true for your use case / target system. Note that if the function is expanded inline, then there is unlikely to be any difference as you may end up with identical assembly in either case. Even if not, the difference may be extremely small and hard to measure.

eerorika
  • 232,697
  • 12
  • 197
  • 326