Chapter 11
References

take a look at this code:

 
Vec sum(Vec pos1, Vec pos2) { 
  return pos1 + pos2; 
} 
 
5// someplace else 
Vec p1(0.1, 0.3, 0.5); 
Vec p2(1.9, 2.7, 0.5); 
 
Vec p3 = som(p1, p2);  
10

Although the sum function above will give you the expected result, it is far from optimal. Your application has to do quite a lot of work to calculate the result and store it in p3.

You already know that a function doesn’t know a thing about what is happening in the rest of your application. In this case that means the function will receive two values, somehow calculates the sum of those values and returns the result to the application.

But how is it able to do so if it doesn’t ’see’ the reset of the application? How does it know the values of its arguments? And how does it know where to put the result? The answer is quite simple, actually: at the moment the application needs the function sum to calculate something, it will copy two values to the function. Afterwards, the result is copied back to the application.

The bad news: all this copying around takes time. Below are the steps that are needed to execute the function sum.

And consider this: this function’s arguments are simple vectors! What if it would be containers with thousands of element? Or maybe you will use this function so much it eventually gets called a thousand times each second!

In other words: When you want speed and performance (and is there really a scenario in which you don’t?), avoid unneeded copies in your application.