Unity Tip – Use StringBuilder Instead Of +=

We Are All Accustomed To +=

Whenever you wish to concatenate two strings in your project, at some point you probably ended up doing something like:

string myString += "myOtherString";

The reason? It is of the first things you are probably taught to be able to do while programming, and it’s super easy to keep using, especially if you need to make a really long string.

The only issue on the long run, is that if all the text in a project is generated this way, it might have an impact on game performance, WITHOUT BEING “DRAWN” in the scene. So you might want to take a look at it.

Instead of the normal operation, you should do something like the following:

StringBuilder _sb;

private void Awake(){ _sb = new StringBuilder() }

private void CleanStringBuilder() { _sb.Length = 0; _sb.Capacity = 0; )

public string Concatenate(string stringOne, string stringTwo)
{ 
	CleanStringBuilder();
	_sb.Append(stringOne);
	_sb.Append(stringTwo);
	return _sb.ToString();
}

Of course, this seems like a lot of work for a few rescued bytes here and there.

Which is why I suggest using the StringBuilderExtension class over at the Unity Tools Repository, to be able to do the following:

string myString = "Hello".Append(" beautiful", " sparkly", " world"); // Results in: "Hello beautiful sparkly world".

So you don’t need to make ANY prep work involving StringBuilder for each class.

What you just read about was ONE of several programmer tips that are available on the Unity Tips Wiki.

So if you liked the one you just read, be sure to check it out (or star it) as it gets updated often! 😮


Interesting how we all grow used to the “dirty” implementations huh? Well, it is better to know that later over never.

This concludes today’s post.

 But Like Always…

Thank you very much for reading my blog :3


Are You A Game Developer?

Hello! Glad to see other fellow indie devs around here 🙂

Just wanted to extend you an invitation to subscribe to the GAME DEVELOPER newsletter for FREE.

Don’t worry, you will ONLY receive notifications on game development content, which include helpful game development tutorials, tips and tricks, and updated on new FREE dev tools and programming tips directly on your inbox.

Leave a comment

Website Powered by WordPress.com.

Up ↑