拆箱和裝箱
阿新 • • 發佈:2021-02-08
技術標籤:日記
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections;
using System.Diagnostics;
namespace ConsoleApp1
{
class Array1
{
static void Main(string[] args)
{
int[] arr = new int[10];
for (int i = 0; i < 10; i++)
{
arr[i] = i;
Console.Write(arr[i] + " ");
}
Console.ReadLine();
ArrayList a = new ArrayList(10);
for (int i = 0; i < 15; i++)
{
a.Add(i);
Console.WriteLine(a[i] + " ");
}
Console.Read();
//Array1 b = new Array1(20);
//for (int j = 0; j < 10; j++)
//{
// b.AddLast(j);
//}
//b.AddFirst(66);
//b.Add(2, 5);
//b.Remove(2);
//Console.WriteLine(b);
//Console.Read();
int m = 10000000;
Stopwatch t1 = new Stopwatch();
Stopwatch t2 = new Stopwatch();
Stopwatch t3 = new Stopwatch();
Stopwatch t4 = new Stopwatch();
Console.WriteLine("測試型別物件int");
t1.Start();
List<int> l = new List<int>();
for (int i = 0; i < m ; i++)
{
l.Add(i);//不發生裝箱
int x = l[i];//不發生拆箱
}
t1.Stop();
Console.WriteLine("List'time: "+t1.ElapsedMilliseconds + "ms");
t2.Start();
ArrayList a = new ArrayList();
for (int i = 0; i < m; i++)
{
a.Add(i);//發生裝箱
int x = (int)a[i];//發生拆箱
}
t2.Stop();
Console.WriteLine("ArrayList'time: "+t2.ElapsedMilliseconds + "ms");
Console.WriteLine("測試引用型別物件string");
t3.Start();
List<string> l2 = new List<string>();
for (int i = 0; i < m; i++)
{
l2.Add("X");//不發生裝箱
string x = l2[i];//不發生拆箱
}
t3.Stop();
Console.WriteLine("List'time: " + t3.ElapsedMilliseconds + "ms");
t4.Start();
ArrayList a2 = new ArrayList();
for (int i = 0; i < m; i++)
{
a2.Add("X");//發生裝箱
string x = (string)a2[i];//發生拆箱
}
t4.Stop();
Console.WriteLine("ArrayList'time: " + t4.ElapsedMilliseconds + "ms");
Console.Read();
}