Pass by value faster than pass by reference

后端 未结 8 2068
不思量自难忘°
不思量自难忘° 2020-12-23 02:48

I made a simple program in c++ to compare performance between two approaches - pass by value and pass by reference. Actually pass by value performed better than pass by refe

8条回答
  •  悲哀的现实
    2020-12-23 03:03

    Quite often executing 32 bit memory manipulation instructions is slower on a native 64 bit platform, because the processor has to run 64 bit instructions regardless. If it is done correctly by the compiler, 32 bit instructions get "paired" at the instruction cache, but if a 32 bit read is executed with a 64 bit instruction 4 additional bytes are copied as filling and then discarded. In short, value being smaller than pointer size does not necessarily mean it's faster. It depends on the situation and on the compiler, and should absolutely not be taken into consideration for performance except for composite types where the value is definitely larger than the pointer by a magnitude of 1, or in cases where you need the absolute best performance for one particular platform without regards to portability. The choice between passing by reference or by value should depend only on whether or not you want the called procedure to be able to modify the object passed. If it's only a read for a type smaller than 128 bits, pass by value, it's safer.

提交回复
热议问题