C# List elements lifetime

I just used List of string to store words from json file. I parsed the json and stored the values in the List. My script looks like this.

public List <string> a = new List<string>();

void Start()
{
    //JSON Parsing 
    var jd = JSONNode.Parse(jsonString);
    print (jd.Count);
    for(int no=0; no<jd["A"].Count;no++)
    {
	    a.Add(jd["A"][no].Value);
    }
    print ("A => "+a.Count);
}

If I have 10 values from json, it is added to the List a. I get the print “A => 10”. When I stop and run my project again my start method again does parsing and adds value to List a. But my List count is now 20. And if I run again, it will be 30 and so on. I tried it on device also. On device after uninstalling and again installing, I get it added to the still get the count as 10. Is it always necessary to clear() the List in the Start() to make the count 0? If I am not doing Clear() before adding strings to List, it always keeps previous values even after stopping the app on editor and on device also.

Do you have the attribute ExecuteInEditMode on your class? That would run Start during edittime and add the strings to the list in edit mode. Since your List “a” is public it would be serialized in the editor so the values are preserved. If your setup looks like this you should either removed ExecuteInEditMode (which causes a lot such problems) or make the List private or use the NonSerialized attribute on the List variable.

If you use SimpleJSON your way of processing the object is very inefficient. You should do something like:

var jd = JSONNode.Parse(jsonString);
foreach(var N in jd["A"].Childs)
{
    a.Add(N.Value);
}

or if you want / need to use an indexed loop, do it like this:

var jd = JSONNode.Parse(jsonString);
var a = jd["A"];
for(int no=0; no<a.Count; no++)
{
    a.Add(a[no].Value);
}

Objects are stored in a dictionary, so each access with [“A”] have to search the entry in the dict. Dictionary are quire optimised but still require some iterations. In your code you access jd[“A”] two times per iteration.