Would you always create a variable for new objects?

The question I often ask myself is, if you need to call one method on an object, is it best to use a variable? So far I have guessed that the answer is Yes - what are your choices and reasons for this?

With variable:

MyObject mo = new MyObject(); mo.MyMethod(); //mo not used again 

Without variable:

 new MyObject().MyMethod(); 

I'm especially interested in .NET, however, if there are any dangerous dots in other languages, I would also rather be warned.

+4
source share
7 answers

As you described this, there is no effective difference between the two alternatives. But if you often need to instantiate an object, just to call one method; should you consider whether your design is right? Do I need to have all these short-lived objects? Remember that for each placement of objects, the garbage collector must ultimately put together a link.

+6
source

An alternative way would be to use static methods. This way you can avoid creating a new object.

 public class MyClass { public static int GetSomeInt() { //do something } } 
+9
source

No, I often call method calls, especially with LINQ:

 var query = source.Where(...) .Select(...) .Take(10); 

Additional variables can be useful if you want to debug an intermediate value and explain the intermediate value (via name), but otherwise there is no real problem.

+7
source

Your two statements are almost identical at the IL level, so do whatever is more accessible to you.

+4
source

There is a technical difference, albiet is secondary ... When using a variable, you tell the compiler to create an additional memory slot in the stack, in the currently running method stack, to hold the link (address) of the newly created object (if the compiler does not optimize it)

when you simply “hook” the syntax of a new object () with a call to its method or member property, this link is not stored anywhere, therefore (again, if the compiler does not optimize it), it should be a little faster.

+1
source

I prefer to use a variable that is more readable.

In my case, since you ask, in C ++, when assigning a new variable on the heap (with a new one), I always check for a NULL pointer (and in some cases, check for exceptions).

0
source

I would be inclined to your "without variable" exposure, especially if this object will no longer be used.

  • This gives more concise code.
  • Since you perform one function, one line is good.
  • However, it is more likely that a more complex procedure may arise due to increased complexity.

Ultimately, go with which template creates the most comprehensible / supported code for you. As you noticed, with each template there are pros and cons.

0
source

All Articles