Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String Creation

Tags:

string

c#

.net

I have a question about string creation in a loop following is a code sample:

 static void Main(string[] args)
    {

        for (int i = 1; i <= 1000000; i++)
        {
            Add(GetStr());
        }

        Console.WriteLine("hmmmmmmmm");
        Console.ReadLine();
    }

    public static string GetStr()
    {
        return "OK";            
    }

    public static void Add(string str)
    {
        list.Add(str);
    }

How many number of strings will be created in memory in case of above code ???

like image 321
Numan Hanif Avatar asked Dec 05 '22 04:12

Numan Hanif


2 Answers

How many number of strings will be created in memory in case of above code

One. (or actually two if you include "hmmmmmmmm")

This method returns a constant string literal:

public static string GetStr()
{
    return "OK";            
}

It is compiled into something like the following IL code:

ldstr "OK"
ret

The LDSTR opcode will push a reference to a string literal stored in metadata and the RET opcode will return that reference.

This means that "OK" will only be allocated once in the metadata. All entries in the list will refer to that instance.

Notice that string literals are interned by default. So no "temporary string" will be allocated before being interned and therefore no garbage collection is needed.

like image 159
Mårten Wikström Avatar answered Dec 25 '22 20:12

Mårten Wikström


I have modified your code so that you can see the Memory addrese of the string "OK"

using System;

namespace ConsoleApplication4
{
  using System.Collections.ObjectModel;

  public class Program
  {
    static unsafe Collection<string> list = new Collection<string>();

    static unsafe void Main(string[] args)
    {
      for (int i = 1; i <= 10; i++)
      {
        Add(GetStr());
      }

      foreach (var str in list)
      {
        fixed (char* ptr = str)
        {
          var addr = (IntPtr)ptr;
          Console.WriteLine(addr.ToString("x"));
        }
      }

      Console.WriteLine("hmmmmmmmm");
      Console.ReadLine();
    }

    public unsafe static string GetStr()
    {
      return "OK";
    }

    public unsafe static void Add(string str)
    {
      list.Add(str);
    }
  }
}

------------ Console Output ------------------------

As you see the list use the same memory reference for the string "Ok".

#225bf54
#225bf54
#225bf54
#225bf54
#225bf54
#225bf54
#225bf54
#225bf54
#225bf54
#225bf54
hmmmmmmmm
like image 32
Bassam Alugili Avatar answered Dec 25 '22 20:12

Bassam Alugili