Friday, February 16, 2007

Java vs C# - Virtual methods

In Java, instance methods are virtual by default—they can be overridden in subclasses unless they are explicitly declared final. In C#, by contrast, instance methods are non-virtual by default. To make a method virtual, the programmer must explicitly declare it virtual. Why is non-virtual the default in C#?

There are several reasons. One is performance. We can observe that as people write code in Java, they forget to mark their methods final. Therefore, those methods are virtual. Because they're virtual, they don't perform as well. There's just performance overhead associated with being a virtual method (more on this in the next mail). That's one issue.

There are two schools of thought about virtual methods. The academic school of thought says, "Everything should be virtual, because I might want to override it someday." The pragmatic school of thought, which comes from building real applications that run in the real world, says, "We've got to be real careful about what we make virtual."

So Java sticks to the academic school of thought and c# for performance sticks to the second school of thought

So if u think of performance in java better to mark your methods with the final keyword for methods that you don’t think clients should not override.

This may be not a performance problem at all with hardware in this era, but in performance related systems even the small bit counts !!!.

 

 

 

 

No comments:

Post a Comment