Tags

Which of the following should execute faster?

If you guessed any of them, you are wrong. That’s right, calling them 10000 times a second there is no single method that consistently executes faster than the others. (Not entirely true but I’m making a point here.)

So the compiler optimised out the literal string for us, that’s good to know. Lets look at the profile results.

tagtest

J’accuse. Everything is allocing but CompareTag, the method in gameobject that is recommended by Unity as the method to, you guessed it, compare tags. Where at all possible use CompareTag. the GC is your enemy. It’s an interesting situation. The alloc comes from get_tag(), which is triggered by the .tag property, which could be a call to unity native code that results in a mono string being created or just due to the immutable nature of strings in mono. I know I’m guilty of it too but if you can find a .tag anywhere in your code base do your darnedest to get rid of it.

Strings

Speaking of strings. String concat or string.Format or StringBuilder for simple wave counter in JSD.

Format looks nicer, kinda, probably a lot if you like printf.

stringtest

Well crap, Format is out, it’s the slowest and the most trashy. StringBuilder vs regular concatenation is a bit trickier. For my purposes I can avoid calling the function for all but when the current wave actually changes, so less than once a second, keeping the alloc as low as possible suits me.