C#/.NET(14): struct와 class의 차이(2)
struct를 사용하게 되는 경우
- 다룰 타입이 논리적으로 단순하고 메모리 관점에서 사이즈가 작은 경우
-
타입이 immutable 인 경우
-
타입이 짧은 생명주기를 갖는 경우
- 타입이 다른 오브젝트에 빈번히 임베드 되는 경우
immutable type? mutable type?
immutable type은 대표적으로 string 이 있다.
immutable type은 콜할 때 마다, 메모리에서 새로 생성이 되는 구조이다. 예를 들어 아래 코드와 같이 반복문이 돌 때마다 힙 영역의 str 주소는 그대로 있고 데이터만 붙여 넣어지는 구조가 아니라 박복문이 도는 만큼 새로운 주소에 데이터가 저장되고 콜할 때 붙여지는 구조라 이해하면 된다.
[struct 없이 immutable 반복 콜 - 소스코드]
using System;
namespace immutable
{
internal class Program
{
static void Main(string[] args)
{
string res = String.Empty;
for (int i = 0; i < 100; i++)
{
res += "Hello";
}
Console.WriteLine(res);
}
}
}
[struct 없이 immutable 반복 콜 - CIL]

그렇기 때문에 immutable type을 빈번히 콜하는 어플리케이션이라면, struct로 type을 관리하는 것이 유리하다.
그렇다면, struct에서 immutable type을 관리하면 어떻게 될까? 위 소스코드와 동일한 로직으로 struct만 사용하여 코드를 작성하고 CIL 코드를 열어보면, struct가 꼭 필요함을 알 수 있다.
[struct로 immutable 반복 콜 - 소스코드]
using System;
namespace immutableStruct
{
struct add
{
public string join(string a, int b)
{
string res = String.Empty;
for (int i = 0; i < b; i++)
{
res += a;
}
return res;
}
}
internal class Program
{
static void Main(string[] args)
{
var obj = new add();
Console.WriteLine(obj.join("Hello", 100));
}
}
}
[struct로 immutable 반복 콜 - CIL]

CIL의 코드 행의 갯수와 코드 크기만 봐도 struct를 통한 immutable type의 성능을 확인할 수 있다.
mutable type은 value type에 속한 대부분의 type이라 이해하면 될 것 같다.
struct와 class 비교
- struct는 value type이고 class type은 reference type이다.
- struct에 consturctor를 사용하려면 반드시 매개 변수가 필요하다.
- struct는 매개 변수가 없는 constructor를 가질 수 없다.
- struct는 destructor를 가질 수 없다.
이 정도로 비교해볼 수 있을 것 같다.
댓글남기기