Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 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
1
Question by theredace · May 21, 2018 at 03:53 PM · array

Uses for anonymous methods

I'm trying to better understand the real world use of anonymous methods. I know how to use them, I'm just trying to better understand WHY I would.

I've read a lot about them, trying to answer this question for myself, and one of the primary reasons people tend to mention is that they're marginally faster to execute than direct function calls. So if that's true, why wouldn't I ALWAYS use anonymous methods? Most documentation and tutorials say that you should only use them for very short functions, but why? If they're faster, then who cares about the length? Is it just an issue of readability? I'll admit that anonymous methods are bit harder to read at a glance, but I'll get over it if they're faster. If I'm storing the anonymous method in a delegate then I can call it just like any named method, I can add it as a listener to another delegate, etc. so I'm not sacrificing any usability as far as I can see.

The one place I can definitely see a benefit in anonymous methods is in the ability to declare the anonymous method INSIDE the function call. So in that case I don't even have a delegate variable, I just pass the entire function body. Speaking of readability, that's pretty hard to read, but I can certainly see the benefit in that.

Am I missing something?

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 fafase · May 21, 2018 at 04:26 PM 0
Share

https://stackoverflow.com/questions/7048850/are-lambda-functions-faster-than-delegates-anonymous-functions

1 Reply

· Add your reply
  • Sort: 
avatar image
0

Answer by Bunny83 · May 21, 2018 at 04:28 PM

You got some things wrong here.

First of all why do you think anonymous methods should be faster than any other method? That's simply not true. An anonymous method is just exactly the same as a normal method, just that it doesn't have an explicit name. Under the hood the compiler actually creates an actual method (with an internal name).


When passing a lambda expression or an anonymous method to another method as parameter you don't pass the method body. You actually pass a delegate reference to the method.


Anonymous methods can represent a closure. So you have to be careful how you use them because you can easily create a lot of garbage due to the closure context that is created every time.


Anonymous methods are just "standalone" method. They are usually created in an internal private class that the compiler generates. "Normal" methods of a class can be virtual and can be overridden in derived classes. You can't do this with anonymous methods


How and where you use anonymous methods is up to you. It's just a tool. Though in most cases anonymous methods are only used for short linq selectors / predicates where the closure ability is the actual advantage.


Finally i just want to point out this is called an anonymous method:

 DoSomething(delegate(string s) { /* your methos body here */ });

while this is a lambda expression:

 DoSomething((s)=>{ /* your methos body here */ });


Lambda expressions are similar to anonymous methods but have some advantages:

  • They have a shorter syntax

  • Depending on the usage the compiler will infer the parameter and return type from the usage if possible


If "DoSomething" expects a delegate that takes a string parameter, those 4 examples are the same:

 DoSomething(s=>Debug.Log(s));
 DoSomething((s)=>Debug.Log(s));
 DoSomething((string s)=>{ Debug.Log(s); });
 DoSomething(delegate(string s) { Debug.Log(s); });





Comment
Add comment · Show 3 · 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 fafase · May 21, 2018 at 04:50 PM 0
Share

I like anonymous for short void parameterless method. I feel when they are supposed to get parameters and return value, they lose readability. That's just personal.

avatar image theredace fafase · May 21, 2018 at 05:09 PM 0
Share

Yeah, I can definitely see that.

avatar image theredace · May 21, 2018 at 05:05 PM 0
Share

Thanks for the detailed response.

First of all why do you think anonymous methods should be faster than any other method? That's simply not true.

I believed this to be true because of a number of sources that say exactly that. Search YouTube for "C# anonymous methods" and the #1 video you get with the most views is this one: https://www.youtube.com/watch?v=drgsIO5$$anonymous$$8ok which shows a simple implementation of an anonymous method and a named method, loops a function call to each one 1000 times and records the time it took for each using the Stopwatch class. The anonymous method approach is significantly faster (the named method loop takes about 3 times longer in this particular example). Is that wrong? Am I misunderstanding this? $$anonymous$$y takeaway from that video is "if anonymous method calls are faster, then why would I ever use a named method?". If I'm implementing it correctly and not worried about closure garbage, and I don't need to override it, then why not use an anonymous method? But clearly people DON'T use anonymous methods for everything, so I'm missing something.

When passing a lambda expression or an anonymous method to another method as parameter you don't pass the method body. You actually pass a delegate reference to the method.

I know that you can pass a delegate reference, but that's not what I'm talking about. You absolutely can pass the entire anonymous method body as an argument. See the 3rd example here: http://www.tutorials$$anonymous$$cher.com/csharp/csharp-anonymous-method $$anonymous$$y point was just that I do see this as a potential benefit because I don't have to declare a delegate member variable if I don't need it outside of this function argument.

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

99 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 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 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 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 avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Static array with custom class? 1 Answer

How can I make an NPC follow a path specified by an array? 0 Answers

Referencing arrays with a variable 1 Answer

Simple Looping drag and drop game 1 Answer

Efficient wind on clouds 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