I have a speed question for Java. I am making a chess program, and I want to check if is a good idea to use one int as a variable to store four int variables, in which the values range from 1 to 4 bits.
The problem is that I’ll often have to extract and put in new parts of the variable, so that will cost quite some bitwise operations.
Code:
int fromX = 4, fromY = 5, toX = 6, toY = 7;
int move = 0
move |= toY;
move = move << 4;
move |= toX;
move = move << 4;
move |= fromY;
move = move << 4;
move |= fromX;
doWork(move);
or
int fromX = 4, fromY = 5, toX = 6, toY = 7;
doWork(fromX, fromY, toX, toY);
doWork() will do a lot of different things with the coordinates, mostly extract them from the ‘int’, or just use the variables.
Which should I use?
No, this is a Bad Idea™ for a bunch of reasons.
This would be highly inefficient
Very hard to read
(consequently) very hard to debug
Sure, it may save a few bytes here and there, but honestly, I buy my RAM-modules in gigabytes these days.
My suggestion:
Write up your entire chess-program. If you run into performance problems, profile the program to see where the bottle-necks are, and do something about those. (I can guarantee you that you won’t start packing several numbers into an
intonce you reach this point.)