gc allocated/ gc collect

Hey there,
i have some issuce with my garbage collection, so i have some questions,
1:
is it better to do this:

	for (int x = 0; x < List1.GetLength(0); x++) {
		for (int y = 0; y < List1.GetLength(1); y++) {
			List1[x, y] = null; // or new MyType()
		}
	}

than that:

		List1= new MyType[50, 50];

2:
is it better to do this:

Vector2 vec = new Vector2();

void Update () {
         vec.x = 3;
         vec.y = 5;
         Funktion(vec);
}

Than that:

    void Update () {
             Funktion(new Vector2(3,5));
    }

And how to solve this in a better way:

public IEnumerator SpawnEnemys(int count, GameObject enemy) {
	int counter = 0;
	while (counter < count) {
		yield return new WaitForSeconds(Random.Range(5f, 10f));
		Instantiate(enemy, transform.position, Quaternion.identity);
		counter++;
	}
}

2 Answers

2
  1. The first way you’re only going to have garbage for the MyClass instances (assuming you’re removing the only reference to them). The second way you’ll have the garbage for MyClass as well as the list. So the first way is less garbage. But look up object pooling and pool your MyClass objects so you can re-use references to them rather than creating new ones. Of course, if you’re only allocating them at transition points - e.g. between levels or something - then it’s probably not much of an issue either way.
  2. Vectors are structs, and structs are (generally) allocated on the stack and aren’t subject to garbage collection. So the second way is fine and more readable in many cases.
  3. WaitForSeconds is just a normal class, so you can create an instance of it once and reuse it. However if you want a random wait amount you would need to pre-create a bunch of them with various wait times and select one at random. See object pooling again.

First thanks for that nice answer :) 1: thanks i will look at object pooling :) 3: i dont mean the wait for seconds i mean the Instantiate, it created a lot of gcallocated..., but i think i can do this with object pooling too ^^

No, and no. However, nothing you’ve posted here would have any impact on garbage collection. You should use the Profiler in Unity’s editor to figure out which methods are creating garbage. There are several guides online for how to do that. Search for “Unity profiler tutorial” in Google.

If you would be better informed you would know that some of this things in Update Loops causes much data at garbege colllection... read Dave-Carlile post thats a good answer

Good advice on using the Profiler to identify memory allocations.

On which line is it exactly throwing that exception?