Avoiding Allocations When Setting Gradient Color and Alpha Keys on Runtime

Hi there,

I’m currently developing a Unity game where I dynamically set gradient colorKeys and alphaKeys multiple times at runtime with varying values. Since Unity’s Gradient class doesn’t accept Lists (which would allow for reuse), I’m considering pooling these arrays to minimize allocations. Is this a method you would recommend, or is there a better alternative for optimizing this process?

I’d appreciate your advice.

Thanks!

Yeah, caching makes sense in this scenario. Only a maximum of 8 elements is supported for both key arrays, so it’s not a lot of memory that you need to sacrifice to get rid of that garbage generation.

If you’re always calling this from the main thread, then you don’t even need to use a pool, just (up to) 9 arrays:

using System;

sealed class GradientKeyArrayCache<TKey> where TKey : struct
{
    readonly TKey[] array0 = new TKey[0];
    readonly TKey[] array1 = new TKey[1];
    readonly TKey[] array2 = new TKey[2];
    readonly TKey[] array3 = new TKey[3];
    readonly TKey[] array4 = new TKey[4];
    readonly TKey[] array5 = new TKey[5];
    readonly TKey[] array6 = new TKey[6];
    readonly TKey[] array7 = new TKey[7];
    readonly TKey[] array8 = new TKey[8];
    
    public TKey[] this[int index] => index switch
    {
       0 => array0,
       1 => array1,
       2 => array2,
       3 => array3,
       4 => array4,
       5 => array5,
       6 => array6,
       7 => array7,
       8 => array8,
       _ => throw new ArgumentOutOfRangeException(nameof(Index), index, "Only values between 0 and 8 (both inclusive) are supported.")  
   };
}
1 Like

I know there are alot of anti cache/pooling people here. But I think its good to ask yourself if the reference type will be reused often, for example in our game bullet casings, bulletholes, hit effects, arrays for RPC networking etc

Then Yes, those should be cached. Stuff that are reused seldom or are have very complex state to reset then those shouldnt be reused. Our game is a MP game and all our complex state objects need to be synced for new players so we might aswell reuse them.

1 Like