开发者

Are there any performance or contention considerations when using VB.Net "Shared" or C# "static" classes and methods?

I have a C# class library behind a WCF service. The library contains ClassA which is declared as static. This static class has a method MethodA which accepts开发者_运维技巧 a string and uses LINQ to query the database for a translation of the string which it then sends back through the webservice to the client.

My question is whether using a static class and static method in this situation is bad design. Should the class and method be non-static so that each client gets their own instance of the class for performance, contention, or other reasons? Thanks.


I'm personally more forgiving towards static methods and classes than some people might be, so I'd say it depends. Is the static method reentrant and thread safe? Then it might be okay. Otherwise it would probably scale badly.

One problem I see is the data context. With a static method, you probably don't have fine grained control over the life span of the database connection? An alternative might be to make it a non-static class and method, and initializing it in a static constructor of the WCF service. That way you can more easily modify the behavior later if need be.

Actually, static constructors in WCF services are bad, if they have any chance of failing, like the database being AWOL for a second. The point was that it would allow more fine grained control in the service itself.


I agree with what Thorarin has already answered. I usually don't see any harm in static classes, esp. when it contains only static methods that do something and return a result without ever touching any static fields or properties. However, as soon as there are modifications of any of those, that could mean trouble. (Search e.g. for any discussion on Singletons and concurrency here on SO.)

Performance-wise, calling a static method should theoretically be slightly faster than calling a non-static method (although for all practical purposes this will probably never make any significant difference), since the runtime doesn't have to pass a this/Me pointer and because with static methods, there'll definitely be no overhead resulting from virtual method calls.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜