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
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.
To some reasoning: In most popular machines, an integer is 32bits, and a pointer is 32 or 64bits
So you have to pass that much information.
To multiply an integer you have to:
Multiply it.
To multiply an integer pointed by a pointer you have to:
Deference the pointer. Multiply it.
Hope it's clear enough :)
Now to some more specific stuff:
As it's been pointed out, your by-value function does nothing with the result, but the by-pointer one actually saves the result in memory. Why you so unfair with poor pointer? :( (just kidding)
It's hard to say how valid your benchmark is, since compilers come packed with all kind of optimization. (of course you can control the compiler freedom, but you haven't provided info on that)
And finally (and probably most important), pointers, values or references does not have an speed associated to it. Who knows, you may find a machine that is faster with pointers and take a hard time with values, or the opposite. Okay, okay, there is some pattern in hardware and we make all this assumptions, the most widely accepted seems to be:
Pass simple objects by value and more complex ones by reference (or pointer) (but then again, what's complex? What's simple? It changes with time as hardware follows)
So recently I sense the standard opinion is becoming: pass by value and trust the compiler. And that's cool. Compilers are backed up with years of expertise development and angry users demanding it to be always better.