Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How many string objects are created by below code?

Tags:

string

c#

string s = "";
for(int i=0;i<10;i++) {
s = s + i;
}

I have been these options to answer this question.

  1. 1
  2. 11
  3. 10
  4. 2

I have this simple code, I just want to know how many string objects will be created by this code.

I have a doubt, Is string s = ""; creates no object. I dont think so, Please make me clear.

If I append string with + operator, it creates new string, so I think It will be a new object created in every iteration of for loop.

So I think there will be 11 objects created. Let me know If I'm incorrect.

String result = "1" + "2" + "3" + "4";  //Compiler will optimise this code to the below line.
String result = "1234"; //So in this case only 1 object will be created??

I followed the below link, but still its not clear.

Link1

Please cover string str and string str = null case too. What happens If we dont initialize string and when If I assign string to null. So It will be an object or no object in these two cases.

string str;

string str = null;

Later in the code, If I do.

str = "abc";

Is there any programming way to calculate number of objects?, because I think It may by a debatable topic. How can I be 100 % by doing some programming or by some tool? I cannot see this in IL code.

I have tried the below code,just to make sure whether new object is created or not. It writes 'different' for each iteration. It means it always gives me a different object, So there can a possibility of 10 or 20 objects. because it does not give me info of intermediate state(boxing for i when doing s = s + i)

    string s = "0";
    object obj = s;
    for (int i = 0; i < 10; i++)
    {
        s = s + i;

        if (Object.ReferenceEquals(s, obj))
        {
            Console.Write("Same");
        }
        else
        {
            Console.Write("Different");
        }
    }

I'm not agreed by the statement that string str = "" does not create any object. I tried this practically.

    string s = null;
    object obj = null;

    if (Object.ReferenceEquals(s, obj))
    {
        Console.Write("Same");
    }
    else
    {
        Console.Write("Different");
    }

Code writes "Same", but If I write string s = "";, It writes "Different" on console.

I have one more doubt now.

what is difference between s = s + i and s = s + i.ToString().

s = s + i.ToString() IL Code

IL_000f:  call       instance string [mscorlib]System.Int32::ToString()
IL_0014:  call       string [mscorlib]System.String::Concat(string, string)

s = s + i IL Code

IL_000e:  box        [mscorlib]System.Int32
IL_0013:  call       string [mscorlib]System.String::Concat(object, object)

So Whats difference between box and instance here

like image 648
vivek nuna Avatar asked Nov 10 '16 09:11

vivek nuna


People also ask

How many String objects are created by the below code?

The answer is: 2 String objects are created. str and str2 both refer to the same object.

How many objects are created with this code String's new String ABC );?

Two objects will be created for this: String s = new String("abc"); One in the heap and the other in the "string constant pool" (SCP). The reference s will pointing to s always, and GC is not allowed in the SCP area, so all objects on SCP will be destroyed automatically at the time of JVM shutdown.

How many ways can a String object be created?

There are two ways to create a String object: By string literal : Java String literal is created by using double quotes. For Example: String s=“Welcome”; By new keyword : Java String is created by using a keyword “new”.

How many objects will be created for the following code String str1 ABC String str2 new String ABC );?

You will create two String instances.


1 Answers

Well, let's count:

string s = ""; // no new objects created, s assigned to string.Empty from the cache

// 10 times:
for(int i = 0; i < 10; i++) {
  // i     <- first object to create (boxing): (object) i
  // s + i <- second object to create: string.Concat(s, (object) i);
  s = s + i;
}

To test that string s = "" doesn't create an additional object you can put

string s = "";

if (object.ReferenceEquals(s, string.Empty))
  Console.Write("Empty string has been cached");

finally, we have 20 objects: 0 + 10 * 2 (10 boxed ints and 10 strings). In case of

string result = "1" + "2" + "3" + "4";

as you can see the result can be and (will be) computed at the compile time, so just one object ("1234") will be created. In case of

string str; // just a declaration, str contains trash

string str = null; // no objects created
...
str = "abc"; // an object ("abc") created
like image 68
Dmitry Bychenko Avatar answered Sep 28 '22 11:09

Dmitry Bychenko