Wednesday, May 14, 2008

Coding Tip #3 - Late Call by Value Instantiation (C++)

When you have a function that takes anything but a simple data type as a parameter and that parameter is being passed in by value, a copy of the object is created. This may be exactly what you wanted. It is standard behaviour. For example, you probably want a copy of your object when putting the object into a collection.

Figure 1. pass by value

If your method has gaurd clauses to ensure only valid objects are added to the collection then there is a chance your code is being wasteful. The early exit event that occurs when the gaurd clauses are true will mean that the original object copy was not required.

You can improve this by doing a const pass-by-reference. You then use the const reference to evaluate your gaurd clauses. If you exit early, all you have spent is 4 bytes on the stack (32bit of course) and you save on the time it takes to copy.

Figure 2. pass by const-reference with late copy

If your code then needs its own copy of the data, create it as a local variable using the const reference as parameter for the copy constructor.

The benefits are directly related to the following:
  • how many chances for early exit exist
  • the size of the object begin copied
  • whether a deep or shallow copy is occuring
  • how long it takes to copy
  • the frequency of early exit calls in relation to copy calls

No comments: