views:

139

answers:

1

Performance and Design wise what would be the pros and cons

Using a sealed class and events or using a abstract class with a virtual function?

there will only be one listener to the events...

+5  A: 

You shouldn't worry too much about performance in terms of abstract classes, inheritance, and event subscription. These are language constructs designed to make development & maintenance simpler. They aren't really designed with performance completely in mind.

There are better things to worry about when it comes to performance. A few things come to mind:

  • Boxing & unboxing - Try to avoid boxing & unboxing objects too much if you're doing a lot of repetitive or iterative tasks.
  • Reference Types vs. Value Types - Objects created as "structs" are stored by value. This means that the entire value of the object is passed around when sent in memory. This can be more expensive, but its lifetime is more deterministic, so it has an advantage in only existing within certain scopes usually. Objects created as "classes" are stored by reference. When sending a by reference object around through code, you only send the reference to the object, which means less memory to move around. The downside is that because it is allocated to the heap, it's lifespan in memory is less deterministic.
  • Subscribing/unsubscribing to events - This is not so much a performance issue as just a general development mistake. Objects will not be GC'ed unless all events are unsubscribed from. If you keep subscriptions open, your object can remain in memory forever causing a memory leak. Microsoft has good documentation on a WeakEvent pattern to help work around this problem.

You should also read Microsoft's MSDN documentation on Performance. It's a pretty good reference for understanding the real performance killers in .NET. Sealed & abstract classes and event handlers are usually not a performance concern.

Generally, code structure is more important to worry about. Think about how you're working with your data and what patterns you use that could be heavy to execute.

Dan Herbert