LayerMask.NameToLayer() performance

Hello all,
Just a quick question for you coders out there. Does anybody know the time complexity of NameToLayer? Is it O(N) as I suspect or possibly faster?

Never tested it, but if you plan on accessing it a lot (ie in Update), I would cache it on Start

The sane implementation of NameToLayer would be to have a backing dictionary, in which case the cost is the cost of string.HashCode.

Even if it’s a linear search, there’s a max of 32 layers. It’s not going to be very expensive.

If you have performance problems, profile, don’t make guesses at what part of your code is slow.

1 Like

In case anyone googles this, I ran a quick test, 1 mil runs when I cache it as separate fields, 1 mil runs caching in a dictionary, 1 mil runs when I use NameToLayer:

Dictionary cache: 91ms
NameToLayer: 96ms```

So it looks like NameToLayer is fine, unless you use it tens of thousands of times per frame. And even then a dictionary wouldn't help you and you're probably better off generating code with constant integers (0 ms) :smile:
4 Likes