Finding the Closest Enemy

We have been looking at temporary objects and the effect they can have on the performance of an application. As an example I offered a function that can tell the AI of a game which enemy is located closest to the player from a list that was provided as a function argument.

Refer to the previous article for the initial definition of the following function:

Enemy FindClosest(list<Enemy> enemies, Player player);

The conclusion was that it is much better to return a reference to an object than it is to return that object by value. Likewise it is much better to pass a function parameter by reference than it is to pass it by value. We actually have to apply this rule to this function before we can return a reference to an enemy.