2

Reading about the cache-friendly code in this SO question, I want to know if firing and handling events could be more cache-friendly than overriding methods when working with classes in C# (because one of the answers states that one should avoid virtual methods, at least in C++), or there is any better strategy than both approaches?

Community
  • 1
  • 1
Guillermo Gutiérrez
  • 17,273
  • 17
  • 89
  • 116
  • Try to understand *why* virtuals are not cache-friendly. Once you do, it should be obvious that events are even unfriendlier. – Jon Jun 03 '13 at 19:24
  • They solve entirely different problems. I don't see how it's really comparable. Perhaps you should show an example problem, and then solve it with both events and without events. Then a comparison can be more meaningful. – Servy Jun 03 '13 at 19:24
  • @Servy, its because I have created a base Form class, which implements virtual methods, that are overriden in all the derived classes, but I was wondering if could be better to fire events implemented in derived classes rather than overriding methods. – Guillermo Gutiérrez Jun 03 '13 at 19:43

1 Answers1

5

I want to know if firing and handling events could be more cache-friendly than overriding methods when working with classes in C#

In general, no. Events are going to require calling out to a separate class instance, which is going to be in a separate memory location. This is going to have the same (or likely even worse) cache issues than virtual method calls.

or there is any better strategy than both approaches?

Unfortunately, idiomatic C# tends to be non-cache friendly. In order to write cache friendly C# code, you typically want to use struct over class, avoid virtual methods, avoid events, avoid delegates (at least ones with closures), etc. Rico Mariani had a nice blog post on Value based programming which discusses many of these issues in detail.

Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373