问题
I am currently building an API which will be used by a webservice.
I was wondering what performance issues I could meet if I built my API using a large amount of static methods.
The original idea was to build expert objects which act as services.
In a single user environment this approach was great! But I will soon need to port this to a multi/concurrent user environment.
What kind of performance issues might i encounter with this kind of architecture?
Best regards,
Edit:
The static methods hold no static variables and have no side effects. They simply execute a normal routine where everything is instantiated. (ie. vars and objects)
回答1:
There's no particular effect on concurrency. The same rules are true: mutating shared data concurrently is bad. If you have instance methods but they don't mutate anything, you're fine.
There's a difference in general design though - static methods should almost always be thread-safe (i.e. you should make them thread-safe) whereas instance methods don't generally have to be (although you should document your class's thread-safety).
回答2:
I wouldn't be concerned too much with performance issues (Knuth), I'd be more concerned with issues of testability and managing state in a multithreaded environment, primarily to reduce complexity of coding and maintenance, which can drag down a project worse than the occasional performance issue.
You can't mock statics, so code that uses an API that is based on static methods is relatively untestable imho. Not really what you're asking, but please think about the people who are going to use your API.
You should reduce the points where shared data is held among threads to the absolute minimum. This reduces the chances of threading issues. You will probably lose a little efficiency in doing this, but you gain much in ease of coding and maintenance. Imagine how hard it would be to write and test an ASP.NET application if all the pages were static. It'd be a nightmare. You might find yourself going down that road as your API gains features over time.
Also, use a decent DI framework (I liek Unity, may be the best thing to come out of P&P).
回答3:
You don't have to be worried about local variables in a static method. Each thread has their own stack and each call to the method will create a separate copy of the local variable on the stack. For example the SqlHelper methods MS provide in their application blocks use this very technique.
The major issue is static variables. I pretty much never use static variables, I haven't had the need to.
来源:https://stackoverflow.com/questions/511378/net-static-methods-and-its-effects-on-concurrency