→ p52644999:List<object> 打錯是嗎 05/23 02:15
※ 引述《proach (pazroach)》之銘言:
: 舉個很簡單的例子好了
: 像我這種骨子裡是使用 C的人,習慣宣告說
: int [] Numbers = new int [5];
: 之後的程式碼就是 C了。
: 可是我看很多範例程式都使用 List,所以,如果我把上述的方法改寫成
: List <int> Numbers = new List <int> ();
: Numbers.Add(0);....
: 之後以一般的方法使用 Numbers.
: 除了 List有很多 methods可以使用之外,如果單純以程式執行效率來說,
: 哪一種方法比較好呢?
如果要比 T[], List<T>, ArrayList 的話
int[] 的效能應該是""略""小於 List<T> (後面會說 "略" 在哪裡)
而 ArrayList 等於是 List<bject>, 兩個一樣...
所以要用哪一個, 基本上看你自己的需求
再講內部一點點..
在 C# 的 T[] 其實就是包裝過的 System.Arrary
而 List<T> 的話, 大略就是
class List<T>
{
T[] items;
public T this[int index]
{
get {
if( index<_size)
throw OutOfRange;
return items[index];
}
set {
if( index<_size)
throw OutOfRange;
items[index] = value;
}
}
}
事實上, 他比較像 c++中的 vector<T>
本質是 fixed size 的 array, 存取快O(1)
但他可以一直 Add 東西進去越變越大..
如果超過 size 的話, 會重新 alloc 一塊更大的 (一般來說用原本的2倍)
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 140.112.42.112