-6

I suppose an ordinary function call,

void Example(int i)
{
    i=2;
    cout << i;
}
int main()
{
    int i=1;
    example(i);
    cout << i;
}

actually copy the variable and so making another instance inside Example(), using double memory (if I am right).

So, under threaded and heavy load environment, would it imposes big impact on performance? Is it always preferably using pointers, or should pass by reference be better for telling the called function where the memory is?

orb
  • 175
  • 2
  • 13
  • Are you talking about primitive or custom types? – yizzlez Aug 11 '15 at 12:41
  • @awesomeyi actually both – orb Aug 11 '15 at 12:42
  • 1
    A pointer might even consume more memory to be copied around on the stack. – πάντα ῥεῖ Aug 11 '15 at 12:43
  • yes, incase of string passing, sometimes virtual judges give TLE if you pass by value. – Enamul Hassan Aug 11 '15 at 12:44
  • @πάνταῥεῖ I am eager to read some explanation to it – orb Aug 11 '15 at 12:48
  • @manetsus may I know what exactly "virtual judges give TLE" mean, or any reference to that? – orb Aug 11 '15 at 12:52
  • @zenith does it mean that might work for custom large class? – orb Aug 11 '15 at 12:55
  • 1
    @orb You need to remember that dereferencing a pointer/reference is a cache-unfriendly operation. It's usually only worth it for large classes, yes. – Emil Laine Aug 11 '15 at 12:55
  • @orb _"virtual judges give TLE"_ Just forget about that statement. manetsus meant Online Code Judge engines (where you can post code for contests), and TLE means time limit exceeded. But no one cares in real world. – πάντα ῥεῖ Aug 11 '15 at 12:57
  • @orb by this time you got the meaning of TLE, but other information is totally wrong. because execution time is a big fact in the real world. oh! one thing is that to post code is not necessarily for contest only. – Enamul Hassan Aug 11 '15 at 14:08
  • I am actually building a real time platform and is heavily concerned on any latency and performance occurs. I can't do much on the network environment, but at least I hope I could have precise memory controls to get the best performance. Thanks above for mentioning cache-friendly things and I am studying topics around it now. – orb Aug 11 '15 at 15:00

1 Answers1

0

You should generally pass primitive types by value, unless you need to make changes to them inside the function. If you need to modify the passed variable, or if passing large objects, you can pass by reference:

void Example(SomeBigType& i)
{/*Do something with i*/}

If you need to pass a large object, but don't need to modify it, then pass by const-reference:

void Example(const SomeBigType& i)
{/*...*/}

You should probably avoid using pointers for this sort of thing and stick to references.

Carlton
  • 4,217
  • 2
  • 24
  • 40