Pass by value faster than pass by reference

后端 未结 8 2080
不思量自难忘°
不思量自难忘° 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:05

    Imagine you walk into a function and you're supposed to come in with an int value. The code in the function wants to do stuff with that int value.

    Pass by value is like walking into the function and when someone asks for the int foo value, you just give it to them.

    Pass by reference is walking into the function with the address of the int foo value. Now whenever someone needs the value of foo they have to go and look it up. Everyone's gonna complain about having to dereference foo all the freaking time. I've been in this function for 2 milliseconds now and I must have looked up foo a thousand times! Why didn't you just give me the value in the first place? Why didn't you pass by value?

    This analogy helped me see why passing by value is often the fastest choice.

提交回复
热议问题