We started experiencing OutOfMemory crashes that were inconsistent and difficult to reproduce. These crashes were impacting our app store ratings, which made solving them a priority. The inconsistency was the most frustrating part -- the crash would happen on some devices but not others, and not always at the same point in the game.
Identifying the Problem
After consulting AI for guidance, we identified the culprit: "object churning." This is what happens when you allocate excessive objects during frame calculations. In our case, we were creating new Vector2 instances every single frame during movement and animation calculations. Each frame, new objects were being allocated, used briefly, and then left for the garbage collector to clean up.
The Fix
The solution was to replace the frame-by-frame object creation with a single reusable Vector2 instance. Instead of creating a new Vector2 every frame, we now populate the same instance with the needed values during calculations. This eliminated the constant allocation and garbage collection pressure.
Additional Benefits
Beyond fixing the OutOfMemory crashes, the change also significantly reduced animation stuttering. The garbage collector had been causing micro-pauses as it cleaned up the thousands of short-lived objects created every second, which manifested as visible hitches in the animations.
Key Takeaway
When something is being done every frame, think hard on what objects are being allocated, or you might run into intermittent issues depending on the device memory capacity. What works fine on a device with 8GB of RAM might crash on a device with 2GB.