Pass by value faster than pass by reference

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

    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.

提交回复
热议问题