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

Asked

Viewed 53 times

2

Which mode is best performatically speaking?

Which way 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();
}

1 answer

2


In terms of performance, mode 1 is probably faster, because it will have to instantiate only once against the other form that will possibly be instantiated more often. There are also nondeterministic factors. There may even be a small difference to help fill the cache, put pressure on the Garbage Collector for longer or with more objects, or something like that, but nothing directly related.

But it’s not so simple, it depends on how and how the methods will be called, how many classes of this kind will exist and other things I can’t even think of right now. Real performance is a tricky thing except in 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 in that object. Of course it needs 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 should only have one object manager, it is strange to create one in each method. If you should have more than one, then it should not be in the object.

It may be that it should not be in the method, nor in the instance, it should be in the class (static). 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.

Anyway the speed difference will be minimal. Probably there are other places that there will be more benefit, maybe not even having this class MeuManager if relevant.

  • Worth the answer, not the p/ be static (is not a system class, is a .dll 3rd), following what you said, I will use mode 1, in addition to being PART of the object, this instance declared in this way facilitates reading (in my opinion), thank you very much.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.