List.Capacity
Capacity is the number of elements that the List can store before resizing is required, whereas Count is the number of elements that are actually in the List.
Capacity is always greater than or equal to Count. If Count exceeds Capacity while adding elements, the capacity is increased by automatically reallocating the internal array before copying the old elements and adding the new elements.
If the capacity is significantly larger than the count and you want to reduce the memory used by the List, you can decrease capacity by calling the TrimExcess method or by setting the Capacity property explicitly to a lower value. When the value of Capacityis set explicitly, the internal array is also reallocated to accommodate the specified capacity, and all the elements are copied.
Retrieving the value of this property is an O(1) operation; setting the property is an O(n) operation, where n is the new capacity.
List
capacity 만큼 메모리를 미리 잡고있는다.
요약 & 생각해야할 점
- capacity를 넘어가면 재할당 후 복사하므로 비용이 크다. (반복문에서 빈번하게 일어날 경우...)
- capacity가 증가될 시 count에 따라 기하 급수적으로 커질 수 있다.
- capacity * T.Size 만큼 메모리를 잡고 있으므로 낭비가 크다. (게임에서는 중요!)
List
ex)
monsters.Capacity = monsterDatas.Count;
foreach(var data in monsterDatas)
{
Monster monsterObj = GameObject.Instantiate(m_monsterPrefab) as Monster;
/// ...
/// ...
monsters.Add(monsterObj);
}
'유니티 & C# 이야기' 카테고리의 다른 글
유니티 FSM: 유한 상태 머신 (2) | 2021.05.30 |
---|---|
문자열을 더해서 만드는 3가지 방법: String Performance (2) | 2018.09.29 |