In terms of performance, what is the best way to declare a variable that will be used in various Actions / Methods in a class?

2

Which way is better performatically speaking?

Which way do you recommend and why?

//Modo 1
MeuManager mm = new MeuManager();

JsonResponse MetodoDOIS(string urlImagem)
{
    var abc = mm.Lista();
}

JsonResponse MetodoUM(ImageUploadContent imageUpload)
{
    var abc = mm.Lista();
}

//Modo 2
JsonResponse MetodoDOIS(string urlImagem)
{
    MeuManager mm = new MeuManager();
    var abc = mm.Lista();
}

JsonResponse MetodoUM(ImageUploadContent imageUpload)
{
    MeuManager mm = new MeuManager();
    var abc = mm.Lista();
}
    
asked by anonymous 19.05.2017 / 15:12

1 answer

2

In terms of performance probably mode 1 is faster because you will have to instantiate only once against the other form that possibly will be instantiated more times. There are also nondeterministic factors. There may even be a slight difference in helping to fill the cache , pressing the garbage collector longer or with more objects, or something like that, but nothing directly related. >

But it is not so simple, it depends on how and how the methods will be called, how many classes there will be and other things that I can not think of right now. Real performance is something complicated but something very contained.

Instance variables should only exist if they are part of the object. This usually indicates that you need to have only one instance on that object. Of course you need to be pragmatic, it may be that performance is really very important, but the correct semantics is more important. And I'm not even talking about readability or ease of maintenance.

If you only have one manager per object, it is strange to create one in each method. If it should have more than one, then it should not be in the object.

It may not even be in the method, nor in the instance, it should be in the (static) class. It has no context to know. This would be even faster because there would only be one instance for every application. It has disadvantages too.

Either way the speed difference will be minimal. There are probably other places where there will be more benefit, maybe not even this MeuManager class if applicable.

    
19.05.2017 / 15:32