Is there a real difference between Array and List? I tested both of them; they look the same in the Inspector and I cannot detect any difference in performance terms between them, so which one is better to use?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Test : MonoBehaviour
{
public List<GameObject> items;
//public GameObject[] items;
private new Renderer renderer;
private void Start()
{
foreach(GameObject cube in items)
{
renderer = cube.GetComponent<Renderer>();
renderer.material.color = Color.Lerp(Color.red, Color.yellow, 0.34f);
}
}
}
Lists are basically just a generic wrapper for Arrays. Arrays need to be initialized by a fixed size, while Lists (from your perspective) have a dynamic size. Internally Lists resize themselfes when necessary.
Technically, Arrays are a bit faster. But unless we consider the dynamic resizing, this difference comes down to a couple of method calls, so it’s neglectable in most to all cases. Use the one more appropriate. If you have a fixed amount of items, use Arrays. If you need a dynamic amount of items, use Lists. Or just always use Lists for convenience if you prefer that.
The only choice that somewhat matters for performance, when talking about arrays, is multidimensional arrays. Dont use those. The access time in multidimensional arrays (array[x,y,z,…]) is multiple times slower than the access time in jagged arrays (array[×][y][z][…]). It shouldnt, but due to some optimizations it is. Unity too did a test on this which you will find somewhere. I dont remember the sample size (i believe it was 100100100), but the time difference was something like 3500ms vs 600ms.
@Yoreki gives a perfect explanation, but there’s one more thing. You have dynamic amounts of items in inspector with both arrays and lists. The real reason to use lists arises if you need to resize it during runtime, like add or remove items when you app is up and running, including running it in editor. If don’t, then you don’t need list. But the difference in terms of perfomance and resources consumption will be so small you wont ever notice.