Home > database >  Difference between assigning object to variable and passing it as argument VS directly creating obje
Difference between assigning object to variable and passing it as argument VS directly creating obje

Time:07-26

What is the difference in both and which is recommended and why?

        var getDetailsReq = new getTransactionDetailsRequest
        {
            transId = transactionResponse.Payload.Id
        };
        var getDetailsCont = new getTransactionDetailsController(getDetailsReq);

vs

        var getDetailsCont = new getTransactionDetailsController(new getTransactionDetailsRequest
        {
            transId = transactionResponse.Payload.Id
        });

The first one holds the address of the object in the memory and it will clean out when dispose off

The second one will go untraceable and will be lost somewhere in memory

makes sense or do you have something to correct me?

CodePudding user response:

Performance wise? Nothing.

Readability-wise? I'd argue that the first one is more readable and maintainable than the second one:

  • You can set a breakpoint on the appropriate constructor when debugging.
  • You can easily inspect / watch the values of getDetailsReq.

CodePudding user response:

If you need getDetailsReq somewhere else in your code, use method 1. Otherwise, it shouldn't make a difference

CodePudding user response:

They are functionally equivalent if the reference is not use again by the caller. It's very possible the optimizer will remove the temporary variable anyway if it is not used by the calling scope.

The second one will go untraceable and will be lost somewhere in memory

Well, you pass it to getTransactionDetailsController, so presumably it does something with the reference. Once the garbage collector detects that no objects have a reference to the object, it will be garbage collected (not disposed).

So use whichever one you feel is better - there is no practical guidance that I know of.

  • Related