What (if any) is the upside or downside (performance, good coding practice, garbage collection etc.) of invoking a non-static method of a class in the manner below:
new ClassA().MethodA(param1, param2);
as against the more “traditional” way of
ClassA classA = new ClassA();
classA.MethodA(param1, param2);
Any thoughts would be greatly appreciated.
Coding
As for coding practice, the second option is better, where the object is stored in a variable first. The reason that makes it better is that you get to name the object according to the context where it’s used. For example:
Performance
As for performance, the first option could be slightly better, since it uses the object directly from the stack and skips the storage of the object in a local variable. It can be seen from the IL of the methods:
IL of first:
IL of second:
This is usually a tiny performance overhead, it’s hard to find a case where it’ll solve a real performance problem.
Bottom line
Since the maintainability of the code gain here is greater than the performance gain it’s preferred to store the object in a variable with meaningful name.