2010年3月27日土曜日

Interfaceは参照型

Interfaceは参照型だったよな。と思い確認。

class Program
{
static void Main(string[] args)
{

Struct s = new Struct();
s.MyProperty = 1;

Interface i = s;
i.MyProperty = 2;

Interface i2 = i;
i2.MyProperty = 3;

Console.WriteLine("s :{0}", s.MyProperty);
Console.WriteLine("i :{0}", i.MyProperty);
Console.WriteLine("i2:{0}", i2.MyProperty);
}
}

interface Interface
{
int MyProperty { get; set; }
}

struct Struct : Interface
{
public int MyProperty { get; set; }
}
結果
image

正解。

つまり、Interface型に代入する際にボックス化が行われているということ。

class Program
{
static void Main(string[] args)
{
var val = new Struct();
var val2 = new Class();

Stopwatch sw = Stopwatch.StartNew();
for (int i = 0; i < 1000000000; i++)
{
object obj = val;
}
Console.WriteLine("struct -> object :" + sw.Elapsed);
sw.Reset();
sw.Start();
for (int i = 0; i < 1000000000; i++)
{
Interface obj = val;
}
Console.WriteLine("struct -> Interface:" + sw.Elapsed);
sw.Reset();
sw.Start();
for (int i = 0; i < 1000000000; i++)
{
var obj = val;
}
Console.WriteLine("struct -> struct :" + sw.Elapsed);
sw.Reset();
sw.Start();
for (int i = 0; i < 1000000000; i++)
{
Interface obj = val2;
}
Console.WriteLine("class -> Interface:" + sw.Elapsed);
sw.Reset();
sw.Start();
for (int i = 0; i < 1000000000; i++)
{
object obj = val2;
}
Console.WriteLine("class -> object :" + sw.Elapsed);
sw.Reset();
sw.Start();
for (int i = 0; i < 1000000000; i++)
{
var obj = val2;
}
Console.WriteLine("class -> class :" + sw.Elapsed);


}
}

interface Interface
{
int MyProperty { get; set; }
}

struct Struct : Interface
{
public int MyProperty { get; set; }
}


class Class : Interface
{
public int MyProperty { get; set; }
}

image

0 件のコメント: