Line creation

I have a question about creating a line in a loop following the sample code:

 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 will be the number of lines in memory in the case of the above code ???

+4
source share
3 answers

How many lines will be created in memory in case of the above code

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

This method returns a string literal constant :

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

It compiled into something like the following IL code:

ldstr "OK"
ret

The LDSTR statement will refer to the string literal stored in the metadata , and RET opcode will return that link.

, "OK" . .

, . , " " , .

+9

, ""

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);
    }
  }
}

------------ ------------------------

, "Ok".

#225bf54
#225bf54
#225bf54
#225bf54
#225bf54
#225bf54
#225bf54
#225bf54
#225bf54
#225bf54
hmmmmmmmm
+5

2 , : "" "". - , "" , , , .

+2

All Articles