How to Avoid unnecessary GC cause by foreach bug(boxing bug)

Hi, Everyone:
We all know that Unity has a boxing bug which can cause unnecessary GC.It’s a terrible thing when you publish your game to handheld device (iphone android). Does anyone has some strategies to avoid the waste.I’ll be very appreciate it!

Consider posting this on the forums. Letting it through in case there is a silver bullet answer.

One solution that works a 100 perdollar is to wait for Unity to upgrade the GC (maybe in Unity 10 or something) to a modern GC from our current time which by then will be 10+ years old :)

@ChoiceXXX could you post a sample script illustrating the 'bug'?

1 Answer

1

Found a way to avoid foreach bug in this stack overflow question: Every iteration of every “foreach” loop generated 24 Bytes of garbage memory?

It suggests the use of for loop instead of foreach. But I’m not sure how long it holds to be the precise solution.

@vexe there is a code snippet in the question above posted by ‘Chris Blackwell’ that illustrates the bug.

Here's a Gamasutra article on Unity-specific memory management techniques. One of the first topics they discuss is the issue of boxing and foreach loops, and they also recommend using a for loop as the simplest method to avoid the issue. To be clear, this is only a problem when looping over a collection of structs, and only when using Unity's built-in compiler.