Oddly slow string combining code (JavaScript)

private var pResNames = new Array(6);
private var pStocks = new Array(6);

function Start () {
	pResNames[0] = "none";
	pResNames[1] = "Soil";
	pResNames[2] = "Work";
	pResNames[3] = "Grain";
	pResNames[4] = "Flour";
	pResNames[5] = "Bread";
}

function Update () {
	... some code to populate pStocks with integers ...
}

function OnGUI () {
	strStocks = "";
	for (i=0; i<pStocks.length; i++) {
		strStocks += pResNames[i] + ": " + pStocks[i] + "\n";
	}
}

In this script, the “strStocks +=…” line rougly doubles my Time.deltaTime for every occurance on a GameObject.

Any ideas why that is, and maybe how to fix/change/workaround this?

Strings in Unity/Mono are immutable which means a chunk of memory has to be allocated each time you add to the end of a string. Also, if you bear in mind that the whole of the stocks string has to be reallocated and copied to the new string buffer each time you go round the loop, then that’s quite a lot of processor time. Worse still, if the pStocks strings are quite long, there is a good chance you will trigger the garbage collector frequently.

Firstly, try changing the line with all the concats to:-

strStocks += string.Format("{0}: {1}\n", pResNames[i], pStocks[i]);

You might find this is enough. If it’s still too slow, create a new string array the same length as the pStocks array. Then, instead of adding to the end of strStocks, assign the new string to the appropriate member of the new array. You can use string.Join to combine the array elements into a single string.

There is also a System.Text.StringBuilder class (see the Mono docs) if you need to construct really big strings.

Thanks. That works great.

Just wish mono / .net had better documentation :wink: