-2

Which of the following calls allocates more garbage?

void LogParams(string format, params object[] args)
{
}

void LogArgs(string format, object arg0, object arg1, object arg2)
{
}

LogParams("Hello, {0}, {1}, {2}", "Tom", "Dick", "Harry");
LogArgs("Hello, {0}, {1}, {2}", "Tom", "Dick", "Harry");

Background is looking into how I can optimise log messages that eventually boil down to string.Format() calls, however many of the log messages are essentially just joining strings together.

JimmyDeemo
  • 313
  • 1
  • 15

1 Answers1

0

First of all, there is no boxing involved since string is not a value type.

The first method uses up more memory, since there has to be created an array with three elements (one for each string reference). Then, each string is created and the references are assigned to the array. Before calling the method, the array refrence is pushed on the stack.

For the other method, only the three strings are created on the heap. The references are pushed directly to the stack before calling the method.

You basically save space on the stack versus saving space on the heap. But the array creation is more expensive (since it's additional).

adjan
  • 13,371
  • 2
  • 31
  • 48
  • Yeah, I see this all now. I mainly got confused about strings so think that is where I got mixed up, thanks for the answer. – JimmyDeemo Nov 03 '17 at 18:20