Last active
April 15, 2021 12:35
-
-
Save Guendeli/454529fce6220f6db531f352cfc6059a to your computer and use it in GitHub Desktop.
Memory Conservation tips for Unity
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Let's talk about memory conservation | |
// If a Unity API returns an array, it allocates a new copy. | |
// Every time it is accessed, Even if the values do not change. | |
// Bad Sample 1: this code allocate too many Arrays | |
for ( int i = 0;i < Input.touches.Length; i++ ) // Get() accessor call + creating copy | |
{ | |
Touch touch = Input.touches[i]; // Creating copy | |
// … | |
} | |
// Good sample: this only allocates one copy of Touch array in memory | |
Touch[] touches = Input.touches; | |
for ( int i = 0; i < touches.Length; i++ ) | |
{ | |
Touch touch = touches[i]; | |
// … | |
} | |
// Very Good sample: using Allocationless API, zero. | |
int touchCount = Input.touchCount; | |
for ( int i = 0; i < touchCount; i++ ) | |
{ | |
Touch touch = Input.GetTouch(i); | |
// … | |
} | |
// Material / Animation / Shader searches by string: BAD | |
// Never address Material, Shader, or Animator properties by name. | |
// Internally, hashes the property name into an integer. | |
// Don't do this | |
void SetMaterial(){ | |
material.SetColor(“_Color”, Color.white); | |
animator.SetTrigger(“attack”); | |
} | |
// but instead, cache them into integers at startup | |
static readonly int material_Color = Shader.PropertyToID(“_Color”); | |
static readonly int anim_Attack = Animator.StringToHash(“attack”); | |
void SetMaterialFast(){ | |
material.SetColor(material_Color, Color.white); | |
animator.SetTrigger(anim_Attack); | |
} | |
/// GET() / SET() problems | |
// Look at this snippet | |
int Accum{ get; set;} | |
Accum = 0; | |
for(int i = 0; i < myList.Count; i++) { // you are internally calling List::get_Count every iteration | |
Accum += myList[i]; // List::get_Value,get_Accum and set_Accum is called every iteration | |
} | |
// over 100 000 elements: 324 milliseconds | |
// now look at this, only one call | |
int accum = 0; | |
int len = myList.Count; | |
for(int i = 0;i < len; i++) { | |
accum += myList[i]; // List::get_Value | |
} | |
// over 100 000 elements: 128 milliseconds, near 3 times faster | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment