- Home /
Define a list while declaring vs in Start()
A list can be defined by using List<T> list = new List<T>();
We can also do something like:
List<T> list;
list = new List<T>();
My question is, what will the difference be between this code:
public class SomeClass {
List<T> list = new List<T>();
}
and this code:
public class SomeClass {
List<T> list;
void Start() {
list = new List<T>();
}
}
In the first the list is initialized upon creation of the object, in the second when you explicitly invoke the Start method as long it is not a $$anonymous$$onoBehaviour.
Answer by Hellium · Nov 26, 2018 at 08:41 AM
There is quite a difference.
When initializing the class variable when declaring it, its value is set when the constructor is called (before Awake
is called)
Initializing the variable in the Start
function will be done latter in the life cycle of the object. It will be done after the object is created, after Awake is called, and the first frame the object is enabled.
So, it's up to you, it all depends on your needs.
Do you also have some input on the impacts on performance? Is there even a difference or is it just the ti$$anonymous$$g?
There will be an impact, but unless your initialization is something very, very heavy (such as calling the constructor of a class calling itself heavy stuff), you won't notice anything.
Supposing you are in this situation, you will have to decide whether the "lag" will happen when the application starts, or when the object is enabled (often, before the first frame of the application)
Well for my application it's not about a large List but about instantiating many items. If every object has a list then even small improvements might help to reduce stuttering in the end. But thanks for the answer :)
Your answer
Follow this Question
Related Questions
A node in a childnode? 1 Answer
Declaring List variable for subclasses with baseclass or without type? 1 Answer
Declaring a type in JavaScript arrays 3 Answers
Serialize a List containing another List (List>) 4 Answers
How to make a combo box 4 Answers