The title to this question isn't written very well. Sorry 'bout that.
I'm curious what the pros or cons would be to increasing the scope of an object instance within a method to the class level.
As a specific example, I have a non-static service class that wraps access to a repository class which is used to manage CRUD activity as well as some other tasks that don't necessarily mix well with other business logic. As I'm building this out, each method creates it's own instance of this repository. Assuming an average amount of traffic (nothing huge), I'd like to know if there's any benefit to creating a class level instance of this repository in the service class' constructor as opposed to the method level scope I'm currently using. This app is not currently using DI, although that might be an option. I'm also considering making the class static, but I have some other hurdles to jump through before that's an option.
Thanks in advance.
Your code doesn't even work yet, and already you're optimizing. Stop, Make your code work, then analyze the performance and optimize for the performance problems you actually have, instead of the problems you think you might turn out to have.
Don't guess wrong and solve the wrong problem, or make things worse!
+1 to John Saunders
In addition to that, let me comment:
I'd like to know if there's any benefit to creating a class level instance of this repository in the service class' constructor as opposed to the method level scope I'm currently using
Is it expensive to create the repository class? By "expensive" I mean has a profiler shown you that it is making a noticeable contribution to the running time of your application.
If so, you might want to cache it in an instance variable. If not, keep it local. As soon as you promote it to an instance variable you bring upon yourself a host of problems such as
using
statement is no longer an option) The old "Global Variables are Evil" quote is IMHO just the most common case of "shared state is evil", which is the actual problem.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.