Challenge: Make a data type for holding one of 8 directions allowing increment and overflow

Richard (Rikki) Andrew Cattermole richard at cattermole.co.nz
Thu Mar 14 01:58:46 UTC 2024


There appears to be a few things that you may not be aware of based upon 
this implementation.

The cost of an add + increment then a bitwise and is only 2-4 cycles on 
a Haswell cpu. Depending upon if its working solely in registers (via 
inlining) or its operating on ram.

The cost of a move from ram into a register is about 1 cycle, but can 
have latencies around 3 cycles if not cached.

Whereas if you need to do branching (if statement, loops), this is an 
unpredictable cost and loops where a simple bitwise operation can be 
done is out right non-optimized.

As for methods like to:

```d
static immutable string[] table = ["north", ...];
return table[this.value];
```

That's two moves from ram to register.

In essence in your design, you have blown out the cost by a significant 
margin well beyond the 12% that is described as being the minimum to 
consider optimization.

If you want to understand where the 12% number comes from I suggest 
reading the paper "Structured Programming with go to Statements" by 
Donald Knuth.

As for exceptions, totally not required. You can solve this by simply 
making your state private so nobody else can mutate it. Bounds checking 
will ensure if the state is corrupted it'll error out if you use the 
lookup method I suggested above.

Understanding what I have said is very important for game engine 
programmers. So if you're interested in it beyond some hobbyist 
endeavors you have some reading up to do ;)


More information about the Digitalmars-d-learn mailing list