Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
3
Question by bleu · Apr 29, 2014 at 10:49 PM · c#foreachmonoheap

Any way to use foreach/for with Dictionary without generating junk?

Since Unity uses an old version of the Mono compiler, there is a bug that causes a heap allocation using foreach (see: http://makegamessa.com/discussion/1493/its-official-foreach-is-bad-in-unity/p1). I use dictionaries a bunch, and I am forced to enumerate over key or value collections of dictionaries (in C#).

Has anyone used viable alternatives to foreach or should I just stomach the allocations? Thanks.

Comment
Add comment · Show 1
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image yoyo · Jun 05, 2015 at 04:27 PM 0
Share

Note that iterating dictionaries goes beyond the $$anonymous$$ono compiler foreach bug. For example iterating the $$anonymous$$eys or Values of a dictionary performs an allocation inside the dictionary implementation.

1 Reply

· Add your reply
  • Sort: 
avatar image
12
Best Answer

Answer by gfoot · Apr 29, 2014 at 11:08 PM

You can use the underlying iterators without creating the unnecessary garbage - essentially, you write what you would have liked the compiler to generate for you. The basic pattern is:

 var enumerator = collection.GetEnumerator();
 while (enumerator.MoveNext()) {
     var element = enumerator.Current;
     // loop body goes here
 }

It is more complex though if the enumerator type is disposable, as you need to dispose of it appropriately, even if exceptions occur in your loop body. There are more details here.

I think in modern parlance you can handle the exceptions more tidily than the linked page does, like this:

 using (var enumerator = collection.GetEnumerator())
 {
     while (enumerator.MoveNext()) {
         var element = enumerator.Current;
         // loop body goes here
     }
 }

In practice though I would guess that any enumerator which requires disposal is going to create garbage anyway, and so you might as well just use the "foreach" in that case.

Comment
Add comment · Show 5 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image bleu · Apr 30, 2014 at 01:58 AM 0
Share

Thanks. What do you mean by disposable (i.e. how would I know it's disposable?)? For the most part my dictionaries use ints or strings as keys. Values are usually classes (typically inheriting from $$anonymous$$onobehaviour). Do you mean implementing the IDisplosable interface as the page says? There are also references to topics related to "unmanaged resources" which I might need to read up on as well.

Also, would it be efficient to just leave out the exception-handling?

avatar image bleu · Apr 30, 2014 at 02:04 AM 1
Share

I just profiled this:

 var enumerator = dummyDic.GetEnumerator();
         while (enumerator.$$anonymous$$oveNext()) {
             // loop body goes here
         }

No garbage generated...interesting! However this version:

 using (var enumerator = dummyDic.GetEnumerator())
         {
             while (enumerator.$$anonymous$$oveNext()) {
               string element = enumerator.Current.Value;
                 //var element = enumerator.Current;
                 // loop body goes here
             }
         }

Generates 28 bytes each frame. Not sure why: it tells me that Update() (where this code is) generates 28 bytes, but does not generate which specific function like Enumerator.$$anonymous$$oveNext() or Dispose.

avatar image hanger · Dec 17, 2014 at 09:01 AM 1
Share

It's the Dispose. Apparently, it's supposed to box according to the official C# spec. Visual Studio doesn't box as an optimization, but $$anonymous$$ono follows the spec. Look here.

The following shouldn't box:

 var enumerator = dummyDic.GetEnumerator();
 try {
      while (enumerator.$$anonymous$$oveNext()) {
          string element = enumerator.Current.Value;
          //var element = enumerator.Current;
          // loop body goes here
      }
 }
 finally {
     enumerator.Dispose();
 }

avatar image bleu · Jan 06, 2015 at 05:36 AM 1
Share

So, you say that Dispose causes a box (related to the allocation), and you said that your example shouldn't do any boxing...but you do a Dispose() call in the finally block. Is there a typo in your example?

avatar image jhina · Aug 18, 2015 at 12:01 AM 0
Share

@bleu: Where's the box in hanger's code? The box occurs in the previous example because of "using". The "using" in $$anonymous$$ono incorrectly casts the enumerator to an object, even though it may be a struct. hanger's code has no box because the enumerator is an explicit type (albeit hidden behind var, but var enumerator is compiled into a true type at compile time.) Thus, if GetEnumerator returns a struct, the code treats it as a struct, and the struct will pop off the stack, no garbage. The explicit call to Dispose is just a call to a method on a struct... which doesn't inherently create garbage either.

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

22 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Multiple Cars not working 1 Answer

Distribute terrain in zones 3 Answers

Simple question about targetting 0 Answers

Question on Using a Foreach Loop on Nested Children 1 Answer

Unity compilation order 2 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges