Everts
Everts

Reputation: 10701

Passing string as parameter

Considering:

void Update(){
    Method("String");
}

I would like confirmation that this is creating a new string each round and then that string is referred by a new variable placed on the stack.

Then is this better:

string param = "String";
void Update(){
    Method(param);
}

I would think this avoid the creation of the new string each round and it is always the same that gets referred to by the stack variable. Also, keeping in mind that the string is only read and not modified.

Upvotes: 1

Views: 537

Answers (4)

Monitor
Monitor

Reputation: 352

void Update(){
Method("String");
}

Definitely there will be one object in the memory,

There are three things you need to know in order to predict what will happen if you had chosen this,

string param = "String";
void Update(){
Method(param);
}

1.Strings are reference types in C#. But this is only part of the picture.

2.They are also immutable, so any time you do something that looks like you're changing the string, you aren't. A completely new string gets created, the reference is pointed at it, and the old one gets thrown away.

3.Even though strings are reference types, strMain isn't passed by reference. It's a reference type, but the reference is being passed by value.

Upvotes: 0

Alessandro D'Andria
Alessandro D'Andria

Reputation: 8868

Try it yourself:

string oldS;
int count;

void Method(string s)
{
    if (ReferenceEquals(oldS, s)) // compare by reference
    {
        count++;
    }

    oldS = s;
}

public void Test()
{
    for (var i = 0; i < 100; i++)
    {
        Method("string");
    }

    Console.WriteLine(count);
}

Run the above code and you can see that output is 99 (the first time isn't counted). Maybe this make you feel safer ;)

Upvotes: 1

dbc
dbc

Reputation: 116595

String literals are stored in an internal pool by the c# compiler, one per assembly, and reused as required. For documentation, see the String.Intern Method

The common language runtime conserves string storage by maintaining a table, called the intern pool, that contains a single reference to each unique literal string declared or created programmatically in your program. Consequently, an instance of a literal string with a particular value only exists once in the system.

For example, if you assign the same literal string to several variables, the runtime retrieves the same reference to the literal string from the intern pool and assigns it to each variable.

More here. You can convince yourself that your string is stored internally with String.IsInterned.

Upvotes: 1

Kirill Bestemyanov
Kirill Bestemyanov

Reputation: 11964

void Update(){
    Method("String");
}

In this example "String" will be interned once and there will be only one object in memory.

Upvotes: 3

Related Questions