C# IList ,ArrayList,list的区别与联系

  
    
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;
using Microsoft.Office.Tools.Excel;
using System.Data.SqlClient;
using System.Collections;


namespace Test
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button5_Click( object sender, EventArgs e)
{
aaa a
= new aaa();
a.AllTest(richTextBox1);
}

private void button4_Click( object sender, EventArgs e)
{
aaa a
= new aaa();
a.Test(richTextBox1);
}

}
// 定义SomeType类型
class SomeType
{
int iTemp = 0 ;
string strTemp = "" ;
public SomeType()
{

}
public SomeType( int i, string str)
{
this .iTemp = i;
this .strTemp = str;
}
}

class aaa
{
#region 比较ArrayList 和Ilist
int k = 0 ;  // 记数器
// 普通测试如果I>400000 时,ArrayList的速度比Ilist慢。在0<I<500是,ArrayList比较快写,在500<i<400000 的时候查不多
public void Test(RichTextBox richTextBox1)
{
System.Diagnostics.Stopwatch sw
= new System.Diagnostics.Stopwatch();
sw.Start();
IList
< SomeType > il = new List < SomeType > ();
for ( int i = 0 ; i < 400 ; i ++ )
{
il.Add(
new SomeType(i, " 汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字 " ));
}
sw.Stop();
richTextBox1.AppendText(
" IList测试 " + " " + k.ToString() + " 测试 " + Convert.ToString(sw.Elapsed) + " \r\n " );

sw.Reset();
sw.Start();
ArrayList al
= new ArrayList();
for ( int i = 0 ; i < 400 ; i ++ )
{
al.Add(
new SomeType(i, " 汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字 " ));
}
sw.Stop();
richTextBox1.AppendText(
" ArrayList测试 " + " " + k.ToString() + " 测试 " + Convert.ToString(sw.Elapsed) + " \r\n " );

k
++ ;
}


#endregion

#region 使用List,数组,ArrayList
public void AllTest(RichTextBox richTextBox1)
{
List
< int > iList = new List < int > ();
int [] iArray = new int [ 0 ];
ArrayList al
= new ArrayList();
int count = 10 ;
for ( int i = 0 ; i < count; ++ i)
{
iList.Add(i);
}
iArray
= new int [count];
for ( int i = 0 ; i < count; ++ i)
{
iArray[i]
= i;
}
for ( int i = 0 ; i < count; ++ i)
{
al.Add(i);//这里有个box操作
}
foreach ( int i in iList)
{
richTextBox1.AppendText(i.ToString());
if (i == iList.Count - 1 )
{
richTextBox1.AppendText(i.ToString()
+ " \r\n " );
}
}
foreach ( int i in iArray)
{
richTextBox1.AppendText(i.ToString());
if (i == iList.Count - 1 )
{
richTextBox1.AppendText(i.ToString()
+ " \r\n " );
}
}
foreach ( int i in al)
{
richTextBox1.AppendText(i.ToString());//这里有个UnBox操作
if (i == iList.Count - 1 )
{
richTextBox1.AppendText(i.ToString()
+ " \r\n " );
}
}
}
#endregion
}


}

我个人认为,数据量超过400000,由于ArrayList有Box 和UnBox 操作,所以运行的时间比较长;在数据小于400000时。Arraylist的

算法可能优于IList,所以建议,数据量少的时候使用Arraylist,数据量大的时候使用ILists

你可能感兴趣的:(ArrayList)