Optimization when using a 2-dimensional array of objects

monkyyy crazymonkyyy at gmail.com
Fri Mar 22 07:34:33 UTC 2024


On Friday, 22 March 2024 at 02:19:07 UTC, Liam McGillivray wrote:
> In the [game I am currently 
> making](https://github.com/LiamM32/Open_Emblem/blob/master/oe-raylib/source/app.d), I have a `Map` class (actually a combination of an interface & class template, but I'll call it a "class" for simplicity), in which there will probably be only one instance running at a time. In that map class is a 2-dimensional dynamic array of `Tile` objects called `grid`. What these `Tile` objects represent are like squares on a chessboard. Their placement in `grid` represents their location on the map.
>

```d
enum tile{wall,field....}
bool ispassable(tile t)=>...
alias grid_=tile[maxhieght][maxwidth];
grid_ grid;
```
your not simplifying anything here with all them oo terms


> Is one option more efficient than the other?

You should probaly do the lazyest thing, factor out your 
"ispassable" logic, like what your walking n of 3, n of 8, n of 
15? so long as you dont do something insane it will be fast on a 
modern computer; allocating several dynamic array that are the 
size of your game world every frame could easily be not very sane.

and if you really really wanted to care, you could precompute the 
"connected compoints" by flood filling across passable tiles with 
a "color" of 0, then finding an empty cell, flood filling with 1, 
etc.; and when you draw the overlay for where you can move you 
can do a heuristic check for a) they are in the same component, 
and b) the manhattan distances before c) doing a greedy check

> Is there a memory allocation technique that would make each 
> tile's location in grid inferrable based on it's memory address?

Yes its called an array
theres some details you need to know and you need to cast 
pointers; just try some trial and error with code like:

```d
int[10] foo;
&foo.print;
&foo[1].print;
(&foo[7]-&foo[0]).print;
```
with whatever casts you need to make it just work


More information about the Digitalmars-d-learn mailing list