Skip to content

SDL_GetKeyboardState called every frame #69

Open

Description

@nickenchev

Very minor detail.

The SDL documentation states the following: "The pointer returned is a pointer to an internal SDL array. It will be valid for the whole
lifetime of the application and should not be freed by the caller."
https://wiki.libsdl.org/SDL2/SDL_GetKeyboardState

This is very common as most SDL tutorials seem to want to call it every iteration of the game-loop, so the idea of having to constantly call it keeps getting propagated into every single SDL tutorial. If the SDL team decides to perform some more work in this function, I bet a whole bunch of SDL based applications would feel a performance hit.

Activity

  1. chalonverse commented on Jul 10, 2024

    @chalonverse
    Contributor

    That’s true — the funny thing is that other parts of the SDL implementation actually also just goes ahead and calls SDL_GetKeyboardState repeatedly, like: https://github.com/libsdl-org/SDL/blob/fdc04708f1950ad76eff16fd47ffe67dcdc5ba04/src/video/windows/SDL_windowsevents.c#L1270

  2. Haruu000 commented on Jul 10, 2024

    @Haruu000

    Contributor

    Hey can you look at the Linux makefile issue

  3. nickenchev commented on Jul 10, 2024

    @nickenchev
    Author

    I'm assuming its because the call itself looks pretty inexpensive when you check the .c file its defined in. Though, the example you sent only occurs on key-up events, so so it wouldn't end up being a part of every loop iteration, it would likely only happen once at the end of a key-press/hold. Whereas the example I noticed it in the book gets called inside ProcessInput(), so its happening on absolutely every single pass of the game loop. Again, not really a big deal, its just something I notice in every sample SDL2 code, and considering how much gamedevs go out of their way to micro-optimize, I always wonder why stuff like this ends up everywhere.

    void Game::ProcessInput()
    {
    ...
        // Get state of keyboard
        const Uint8* state = SDL_GetKeyboardState(NULL);
        // If escape is pressed, also end loop
        if (state[SDL_SCANCODE_ESCAPE])
        {
            mIsRunning = false;
        }
    }
    `
    
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions