C++ Snake Game – Change Coordinates or Spawn New Object for Fruit?

cgame development

I've decided to lean SDL and make a Snake game. I have gotten to coding the spawning of a fruit, which the snake eats to get longer. Every time the snake eats the fruit, the fruit needs to change to a random position on the screen. I can either simply change its coordinates to new random ones, or I can trash the old fruit object (that has been eaten by the snake) and make it point to a new object with new coordinates. Which one is more efficient? Here is some pseudo-code, for reference:

Option 1:

if (snake_eats_fruit) fruit->changeCoordinates();

Option 2:

if (snake_eats_fruit) fruit = new Fruit(); // fruit's constructor sets random coordinates

So should I keep the same object and change its coordinates, or make a pointer to a new object with different coordinates? Thanks!

Best Answer

The first option is probably faster. With the second one you have, at least, the additional memory allocation task.

Anyway this is a good example of premature optimization: performance shouldn't be a concern for this kind of operation.

The snake eats a fruit just occasionally. Between two meals there are a lot of other (complex) events that take place and the action of changing the position of fruit is negligible.

Some aspects you should consider are:

  • do I need explicit memory allocation? (new Fruit()).

    It can be the source of memory/resource leaks and it can be slower (e.g. Why should C++ programmers minimize use of 'new'?).

    If you really need dynamic allocation use a smart pointer

  • with the second option can easily create a dangling pointer

    Fruit *fruit = new Fruit();
    Fruit *fruit2 = fruit;
    
    // Snake eats fruit.
    delete fruit;
    fruit = new Fruit();
    
    // now fruit2 points to something which is not valid anymore
    
Related Topic