Store more references or compute those references real-time?

I’m trying to figure out something fairly specific but I’m sure this could expand into a larger conversation. Or it could be a really short conversation if it has been discussed in depth somewhere else.

I’m building a tile based game and I sometimes need to know the neighbours of a tile, for example when building something… it’s a tile based building game.

Currently every time I want to know a tile’s “Neighbourhood” I use a static class that figures out what’s around it. I don’t imagine it’s super resource intensive to perform that calculation. But it necessitates I keep a reference open to the “Map” a tile belongs to.

I wonder if it wouldn’t be a little bit easier to simply store references to neighbour tiles on each tile. But, if I had a few thousand tiles each storing eight references to other tiles would that be expensive?

C#

I’d recommend doing it the most simple way and address it if the profiler says there’s a problem.

The bottlenecks in your game will almost never be where you expect them, rely on the profiler to tell you where to spend your optimising effort.

2 Likes

Decisions like this one are fairly foundational, maybe I’m writing the code wrong but it seems like it would be a lot easier to make a decision about what direction I want to go with it.

In a way it’s optimising before I need to optimise.

Programming is hard.

Which is a terrible idea :slight_smile:

Honestly, the most fundamental aspect of this is: Unless there are real performance issues with the implementation, do the one that fits your architecture the best and the one that is most simple to implement and maintain.

I very much doubt either solution will be a performance or resource issue.

How many objects are you working with?

A few thousand (let’s say 10,000 for sake of argument):

10,0000 * 64bit reference = 10,000 * 8 bytes = 80 kilobytes, hardly worth even thinking about…

We’d need to understand your algorithm for determining neighbours at runtime to asses the difference in search time vs references. But unless you’re doing some brute force lookup (comparing thousands of objects with thousands of objects) it’s also unlikely to be a bottleneck.

Rule number 1 - use the profiler. Guessing at what will need to be optimised almost never works.

1 Like

As a general rule memory is cheaper then CPU time. However this rule is so general as to be absolutely useless in any practical situation.

Encapsulate it. Properly encapsulated you can change the implementation without having any effect on the rest of your game. Encapsulation insulates you against changing your mind later.

Great advice. Spoken almost word for word from the book I’m reading “Clean code”

thanks for your help guys