0
class foo
{
    string bar()
    {
        const string c = "dead beef";
        return c;
    }

    void Test()
    {
        string a = bar();
        string b = bar();
    }
}

are a and b different instance or are they pointing to the same memory address? (the == comparison would return true regardless they are the same instance or not so I can't really test it)

Steve
  • 11,696
  • 7
  • 43
  • 81
  • 2
    Strings are immutable, so you don't need to know or care. You can use `Object.ReferenceEquals` to find out though. – Blorgbeard Jan 24 '18 at 21:58
  • @Blorgbeard was wondering if im saving some tiny bit of resource for methods that will be called millions of times – Steve Jan 24 '18 at 22:00
  • @Steve Then measure how long it takes to run your method millions of times and see if changing the implementation changes the time. – Servy Jan 24 '18 at 22:01
  • If you'd like to see the difference local `const` variables have on the generated IL, take a look at a question I asked back in '09 - https://stackoverflow.com/questions/1707959/is-there-a-runtime-benefit-to-using-const-local-variables – Richard Szalay Jan 24 '18 at 22:14
  • Imo, this would get inlined anyway, so doesn't matter. The call would never happen. – rokkerboci Jan 24 '18 at 22:20

1 Answers1

1

No, but it doesn't really matter for the majority of cases.

For structs (int, float, DateTime, etc) the value will placed on the stack so the memory reuse isn't relevant.

For strings, const doesn't do anything special but string constants themselves are interned so all matching constant string values will point to the same instance in memory.

Richard Szalay
  • 83,269
  • 19
  • 178
  • 237
  • 1
    interesting. that's why Object.ReferenceEquals(a, b) returns true or string but not int – Steve Jan 24 '18 at 22:04
  • 2
    Because ints are not objects, so they will boxed into (separate) object wrappers so they can be passed to ReferenceEquals. – Blorgbeard Jan 24 '18 at 22:06