Skip to content

Add no-allocation controller retrieval + Controller Support#812

Open
wallstop wants to merge 2 commits intoFacepunch:masterfrom
wallstop:dev/wallstop/no-allocation-controllers-2
Open

Add no-allocation controller retrieval + Controller Support#812
wallstop wants to merge 2 commits intoFacepunch:masterfrom
wallstop:dev/wallstop/no-allocation-controllers-2

Conversation

@wallstop
Copy link
Copy Markdown

@wallstop wallstop commented Mar 26, 2025

The Problem

Currently, controller retrieval through SteamInput.Controllers allocates memory every time it is called due to having to create the enumerator object to statefully walk through yield return. Most games will be running this code inside an Update loop, to retrieve current controller state and fire input events.

The general advice to pretty much all game developers is: "Don't allocate in Update". Doing so will generate huge amounts of garbage, causing the Garbage Collector to kick in over and over, which tanks FPS.

Unity has learned this lesson over the years and has started shipping allocation-free versions of its methods that used to return arrays. See:

// Allocates memory always
public T[] GetComponentsInChildren<T>();

// Doesn't allocate memory (assuming the results list doesn't need to be resized), 
// will populate the provided `results` list with found children
public void GetComponentsInChildren(List<T> results); 

The Solution

I've implemented a simple alternative to the SteamInput.Controllers enumeration, which I've called SteamInput.GetControllersNoAlloc. The implementation is the same, except that it does not allocate an enumerator, leading to less garbage being generated, which results in an allocation-free method that can safely be called during Update

Tests

I have simple tests around equivalence, as well as tests for allocation (existing) v no allocation (this approach) in a simplistic manner.

Extra

In order to try to test this the best I could, I needed to add a fix for bug #512, which are public Init and Shutdown methods. This should also solve #758, which is also solved in #805.

Add allocation tests

PR feedback

Fix compilation bug
@wallstop wallstop changed the title Add no-allocation controller retrieval + public SteamInput.Init method Add no-allocation controller retrieval + Controller Support Mar 26, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant