How important is it to wrap temp variables/objects in a "using" block?

I know that with C# garbage collection happens automatically. But I’ve read that it only happens when memory is needed. Therefore, your game might still be taking up a larger memory footprint than necessary a lot of the time.

So, I’ve read that one way to have some control over garbage collection is to wrap some code in a “using” block. Then whatever temporary variable or object is in that “using” statement will have its memory immediately released at the end of the block, rather than “at some time in the future”.

I’ve shipped several games now, but I’ve never used the “using” keyword in this way. I’m wondering now if I should try to be more diligent about doing that. My instinct says that it doesn’t matter all that much and just makes the code look messier. I’m wondering what others think.

All “using” does is call Dispose on the included variables when the using block goes out of scope, assuming those objects implement IDisposable. It has nothing to do with triggering garbage collection whatsoever. If you’re curious about whether “using” will affect your memory footprint for a certain object, check if it implements IDisposable and thus needs nonmanaged resources released.

Here is a nice clear explanation:

If you find any documentation to the contrary from a reliable source ( i.e. Microsoft or Mono ) please post it.

well im aware of the benefit of using using lol

however i didnt know that C# handled garbage collection that way

Knowing that bit now I would say yes you could get away with it however there would be cases where it would be lethal not to

cases where you suddenly read in a whole lot of information and run them through a slew of temporary variable declarations

(like reading in a LOT of save data)

or something along those lines

its just one of those added optimizations you can do
like StringBuilder

though tbh a person can spend months optimizing the hell out of a script, i believe there is such a thing as “good enough”

Any object you create that references limited, external, non-managed resources - files likely being the most common - should be created with using to make sure those resources are released as soon as possible.

It also makes sure that if any sort of exception occurs while using the resource that it is properly released. Think of it as an “acquire-use-release” sort of pattern for resources.

Not an expert, but USING isn’t for garbage collection.

It’s for “special” things like files, to be absolutely sure the Close statement gets called in every single case. I’d guess that the actual memory used for the file variable isn’t even GCed any faster than normal.

Since Unity wants you to use Resource to read files, hopefully they have all the correct USING’s buried inside there.