Does using delegates slow down my .NET programs?

前端 未结 4 2054
小鲜肉
小鲜肉 2020-12-06 10:20

Does using delegates slow down my programs?

I\'ve been avoiding them because I really have no clue if they make my programs any slower. I know if I cause a (catch

4条回答
  •  一整个雨季
    2020-12-06 10:47

    Just a small addition to Jon's post: when used in the normal C# way (i.e. via lambdas / anonymous methods / event handlers / etc), then they are definitely very quick - but note that another important use of delegates can be to execute dynamic code (either methods built at runtime, or existing methods via reflection and Delegate.CreateDelegate). When used in this second way, delegates offer a very significant speed improvement (compared to reflection Invoke etc).

    So don't be shy about using delegates. And in particular, if in doubt - measure it for realistic code: it is meaningless whether it takes 1 or 100 micro-weasels*, if this still only accounts for 0.01% of your overall execution time.

    *=just some arbitrarily small amount of time...

提交回复
热议问题