I've been putting some (a lot) of thought about how to read keyboard input and especially, when.

Looping through all the keycodes on the keyboard and updating the statuses seems like a lot of waste when there are only few keys pressed at one time.

I started to think that if the game gives a player key rebinding ability, why not read only those keys/actions that are currently bound in the game and ignore the rest?

If the "Move forward" action has a key "W" bound to it, then only look for status of key W.

And you can ignore the rest (Of course not ESC and other various game-wide actions).

To me this would make sense, because most of the time games are simple and they only use a few keys on the keyboard.

Does this approach make any sense?

  • 2
    \$\begingroup\$ Sounds like a premature optimization to me. As a side note, have you thought about an event based system? \$\endgroup\$
    – user35344
    Aug 30, 2016 at 12:58
  • 1
    \$\begingroup\$ Did you run a profiler on your code to realize that this part should be optimized? \$\endgroup\$
    – Vaillancourt
    Aug 30, 2016 at 12:58
  • 1
    \$\begingroup\$ Yes it makes sense to check the keys you are interested for, if nothing ever happens when you press 'C' then why check it? \$\endgroup\$
    – Mikael
    Aug 30, 2016 at 13:00

1 Answer 1


Does this approach make any sense?

Yes. It's nothing new or surprising at all; most games will get keyboard state one of three ways:

  • either they will call an OS function (directly or indirectly) that reports the state of the entire keyboard at once or
  • they will handle events from the OS indicating "this key is down" and "that key is up" or
  • some combination of the above

Both have pros and cons in terms of the semantics you can extract from the key state. For example it is often easier to track continuous, "key is held" actions over several frames if you are using the method that just returns the entire keyboard state. The event-based approach is often more suitable for "instant" key-presses. And of course you can combine both methods for a hybrid solution or track your own key state internally.

Listening for the key events from the OS is the method you're suggesting.

You should make this choice based on the semantics you need. Don't worry about whether or not one option is "slower" or "less efficient" than another, because the little inefficiencies you are thinking of are

  • probably not where you think they are and
  • absolutely nowhere near the critical path of your per-frame performance

In other words, the method you use for keyboard handling is not what is making your game slow, so don't worry about it.


You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .