Home > Back-end >  Are there penalties for just using the new keyword instead of creating a class variable before calli
Are there penalties for just using the new keyword instead of creating a class variable before calli

Time:02-12

Example

(1)

var classVar = new class();

classVar.Method();

(2)

new class().Method();

I like the second way, less wordy.

Is there a performance difference?

Is it considered bad coding practice?

CodePudding user response:

If your Method() doesn't use anything from that class, why is it defined there? You could use namespace instead.

The only difference between your (1) and (2) is that the class instance is destructed immediately in (2).

CodePudding user response:

in your case Method seems to be static (ie there is no useful data stored inside the instance of 'class' (note I am ignoring all the invalid / not recommended name issues). Assuming this is c# but all languages have the same ideas, you would go

public class class{ // ugh
   public void static Method(){
       Console.WriteLine("I am Method");
   }
}

now you can go

 class.Method();

so the code is neatly filed away inside 'class' but you dont have to pay any overhead.

If you really need to instantiate 'class' then presumably you need to do more than just call one method on it. In which case

new class().Method();

makes no sense, since you call create it, call a method and destroy it.

Really a more concrete example is needed

  • Related