Vishal Sharma
Vishal Sharma

Reputation: 2803

will too much extension methods degrads performance ? how it works

I m a great fan of csharp 4.. i have added too much methods to string object (.net types) as an extension method consider approximately 200 will that degrads performance?

is it right to add these much methods in .nets library ? how actually extension methods work internally..?

Upvotes: 1

Views: 703

Answers (2)

Sriram Sakthivel
Sriram Sakthivel

Reputation: 73442

Well, It is not going to affect runtime performance anyway. Since "Extension Methods" are just compiler trick. Under the hood they are just a static methods in a static class.

public static class MyExt
{
    public static void MyExtension(this object obj)
    {
        //Do something
    }
}    
public static void Main()
{
    object obj = new object();
    obj.MyExtension();
    //Above line gets compiled into MyExt.MyExtension(obj);
}

As you can see obj.MyExtension(); gets compiled into MyExt.MyExtension(obj); and it is just a method call only. No need of worrying about performance.

If at all you're worried about performance I'd say it won't hurt "runtime performance" though it may or may not hurt compile time performance, Compiler needs to find whether any extension method defined in current namespace as well as imported namespaces.

That is not going to be hard though, since compiler needs to check only static classes. No library is going to have numerous "static classes".

Upvotes: 4

pixelTitan
pixelTitan

Reputation: 495

There are no performance penalties for using extension methods, however there is such a thing as bad extension method design. There is a great article about the do's and don'ts of extension methods here: The DOS and DONTS of extension methods.

Upvotes: 0

Related Questions