C# 中 string.Empty、""、null的區別

一、string.Empty""

1、Empty是string類中的一個靜態的只讀字段,它是這樣定義的:

// Summary:
//     Represents the empty string. This field is read-only.
public static readonly string Empty;

       也就是說 string.Empty 的內部實現是等於 "" 的。二者在優化方面稍有差別,string.Empty 是 C# 對 "" 在語法級別的優化。這點可以從上面 string.Empty 的內部實現看出來。也就是說 "" 是通過 CLR(Common Language Runtime)進行優化的,CLR 會維護一個字符串池,以防在堆中創建重複的字符串。而 string.Empty 是一種 C# 語法級別的優化,是在C#編譯器將代碼編譯爲 IL (即 MSIL )時進行了優化,即所有對string類的靜態字段Empty的訪問都會被指向同一引用,以節省內存空間。

        PS:MSILMicrosoft Intermediate Language (MSIL)微軟中間語言)。

2、引用類型的數據將對象在堆上的地址保存在上,將對象的實際數據保存在上。string.Empty與 "" 都會分配存儲空間,具體的說是都會在內存的棧和堆上分配存儲空間。因此string.Empty與“”都會在棧上保存一個地址,這個地址佔4字節,指向內存堆中的某個長度爲0的空間,這個空間保存的是string.Empty的實際值。

        代碼如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace string_Empty
{
    class Program
    {
        static void Main(string[] args)
        {
            stringTest();
        }

        public static void stringTest()
        {
            string str;
            string str1;
            string str2;
            string str3;

            str = string.Empty;
            str1 = string.Empty;
            str2 = "";
            str3 = "";
        }
    }
}
        設置斷點後運行結果如下:


 
        可以發現這種寫法下,string.Empty 和 "" 的地址是相同的。  

        由於 string.Empty 定義爲 static readonly ,又根據上面運行結果得知, string.Empty 不會申請新的內存,而是每次去指向固定的靜態只讀內存區域,""也一樣。    

        string.Empty 與 "" 在用法與性能上基本沒區別。string.Empty 是在語法級別對 "" 的優化。

二、string.Empty  "" null 的區別

        代碼如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace string_Empty
{
    class Program
    {
        static void Main(string[] args)
        {
            stringTest();
        }

        public static void stringTest()
        {
            string str;
            string str1;
            string str2;

            str = string.Empty;
            str1 = "";
            str2 = null;
        }
    }
}
        設置斷點後運行結果如下:


        從運行結果可以看出,string.Empty 和 "" 在棧和堆上都分配了空間,而 null 只在棧上分配了空間,在堆上沒有分配,也即變量不引用內存中的任何對象。

發佈了51 篇原創文章 · 獲贊 17 · 訪問量 15萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章