玩轉C#之【CLR】

2022/10/10閱讀時間約 4 分鐘

介紹

原始碼(source code)→編譯器→中繼語言(MSIL)→CLR→電腦看得懂的語言(Native code)
所以我們可以知道,CLR( Common Language Runtime ):是 .NET Framework 的虛擬機器元件 (virtual machine component),用來管理執行中的.NET程序。
📷
📷

Stack(棧)、Heap(堆)記憶體分配發生了什麼?

Stack

  • 儲存實質型別;
  • 先進後出的原則;
  • 是屬於自己維護的,當元素不再被使用會被拋出;
  • 空間較小,訪問速度快;

Heap

  • 堆(也叫做託管堆)存儲 參考型別資料;
  • 空間釋放有垃圾管理機制;
  • 堆沒有訪問限制,按照地址索引;
  • 空間較大,訪問速度比Stack慢;
📷

實質型別(值類型) VS 參考型別(引用類型)

  • 實質型別:
    bool
    byte
    char
    decimal
    double
    enum
    float
    int
    long
    sbyte
    short
    struct
    uint
    ulong
    ushort
  • 參考型別:
    class
    interface
    delegate
    object
    string

小測驗 Part1

public class Student
{
public string Name { get; private set; }

public int Tag { get; set; }

public Student(string name)
{
this.Name = name;
}
public void Show()
{
int iNum = 0;
Console.WriteLine($"This is {this.Name} {iNum} show!");
}
}
這時候,以下四個會放在Stack還是Heap?
student
Tag
Name
iNum
Student student = new Student("小昶");
student.Tag = 1;
student.Show();
答案:
student => Heap
Tag => Heap
Name => Heap
iNum => Stack

小測驗 Part2

public struct Salary
{
public int Base { get; set; }

public string Remark { get; set; }

public void Show()
{
string text = "2020年要消滅貧困人口,準備消失了!";
Console.WriteLine(text);
}
}
這時候,以下四個會放在Stack還是Heap?
salary
Base
Remark
text
Salary salary = new Salary();
salary.Base = 10000;
salary.Remark = "2020年貧困人口";
salary.Show();
答案:
salary => Stack
Base => Stack
Remark => Heap
text => Heap
結論:
參考型別一定會在HEAP裡面,實質型別要看依附的對象而決定
關於C#與IL對比解讀、GC的機制和優化之後會專門寫一篇文章跟大家講解

參考資料

本篇已同步發表至個人部落格
https://moushih.com/2022ithome24/
鐵人賽文章
為什麼會看到廣告
8會員
39內容數
我是這個部落格的作者,喜歡分享有關投資 💰、軟體開發 💻、占卜 🔮 和虛擬貨幣 🚀 的知識和經驗。
留言0
查看全部
發表第一個留言支持創作者!