I am implementing a 2-player game that will be run in a tight loop literally hundreds of thousands of times, being then performance paramount.
My code actually looks something like this:
public class Table {
private final int WHITE_PLAYER = +1;
private final int BLACK_PLAYER = -1;
private final int currentPlayer;
private final int otherPlayer;
...
}
I was wondering if I would get any performance hit would I choose to replace
private final int WHITE_PLAYER = +1;
private final int BLACK_PLAYER = -1;
to an enum defined as
public enum Players {
WhitePlayer,
BlackPlayer
}
I had the idea that enums were just syntactic sugar over integer constants, and taking a glaze look over the bytecode generated for a test enum, as well as the code calling it, seems to indicate that using them is indeed the same as making a static method call but for some enum infrastructure that is set up when it’s first run.
Is my assumption that it is indeed the same to use enums as static constants correct or am I missing something here?
In a micro-benchmark, yes, checking integer constant equality will be faster than checking enum constant equality.
However, in a real application, let alone a game, this will be totally irrelevant. The things that are happening in the AWT subsystem (or any other GUI toolkit) dwarf these micro-performance considerations by many orders of magnitude.
EDIT
Let me elaborate a little then.
An enum comparison goes like this:
An integer comparison for a small integer goes like this:
Obviously, the first is more work than the second, although the difference is quite small.
Run the following test case:
and you will find that the enum comparison is slower that the integer comparison, on my machine by around 1.5%.
All I was saying is that this difference will not matter in a real application (“Premature optimization is the root of all evil”). I deal with performance problems on a professional basis (see my profile) and I have never seen a hot spot that could be traced to something like this.