Data array too heavy for task?

So, I’m implementing my input handler in LWJGL3, doing it on my own (no references) just for the heck of it.

I need to be able to keep track of how long keys have been held down, and my first instinct is to have an array of integers keeping track of the “down” time of individual keys (more precisely, keeping track of the start time).

public static int[] keys_time = new int[65536];


keys_time[key_code] = start_time;

If my calculations are correct, for integers being 32-bits long, just declaring that array takes around 262Kb.

My question here is… Is this a waste of space? Are 262Kb too much? Would it be worth it to do something like this:

public static HashMap<Integer, Integer> keys_time = new HashMap<Integer, Integer>();


keys_time.put(key_code, start_time);

My intention here is not to discuss about keyboard handlers (I’ll check documentation on that later today), but to discuss the ramifications of making design decisions like the above.


Please see:
(i.e. your array only needs to hold 348 entries)
LWJGL3 JavaDoc:

And in any case, only at most a very small number of keys can be actually held down at the same time.
By all means use a HashMap to get it working. If for some bizarre reason you’re concerned about a few kb more than you’re concerned for your time or sanity, write your own super optimised map of keycodes to durations using integers and a simple for…loop lookup instead of a hash, it won’t be any slower.

Cas :slight_smile:

Thanks for the references and examples! :slight_smile:

For the record, I’m using that massive array because I was following a basic tutorial on LWJGL3 input handlers that had it defined as such.

In any case my worry is about the cost of merrily allocating large static arrays, like the one I mentioned, all across the program. 262kb might not seem like much (well it does feel huge to me anyway) but I suspect it can add up rather quickly.

I could not resist writing (yet another) simple specialized Int/Long Map:
When you do lots of puts followed by remove, as is typical for pressing/releasing keys, then it’s about 2.5 times faster than HashMap but still an aweful lot of times slower than simple direct long[] array access. (measured with JMH)
So use it only if you really want to save that 1KB of memory…, which you probably don’t want to.

Are your keys analog?

Yup, analog, no virtual keyboard or the like.

Analog as in all your keys have values other than up/down?

Oh, no idea, I assume those are the only values I get.