Accessing parameters through a long chain of classes slower?

Does putting this long reference to a texture:
StaticGlobal.assortmentData.deliveryCollections*.capsuleCollection[i2].items[ itemCounter ].texture*
in a bunch of places cause performance to drop more so than going like
Texture myTex = StaticGlobal.assortmentData.deliveryCollections*.capsuleCollection[i2].items[ itemCounter ].texture*
and then using ‘myText’ in all those various locations?

Really it won’t make a difference to the game performance, because whether you use the variable or not it’s still calling the same function. The variable does; however, make it faster to type and makes the script look cleaner.

Actually, it will probably make it faster. The only way to be sure, though, is to actually benchmark it. Sometimes the compiler will straighten things out, and sometimes it won’t.

Creating your own pointer is absolutely faster! Your first example is 5 address lookups, but once you have myTex it’s only one address lookup.

Caveat: This is how it works in any other standard compiled environment, and I’m just assuming Unity does the same.

i would also choose the second way when to iterate often over the same expression or change the same object frequently. if you have to assign another value to your cache variable each iteration or access is useless.

so in a “in a bunch of places” its definitely worth to cache it.

and beside the performance this also increases readabilty abd reduces the occurence of bugs (for example when you forget to change an occurence of the long version).

Cool, thank you.

So I can see how this would work very easily with a Texture, as a Texture is allocated on the Heap.
And Texture myTex = chainOfLookups.lookedUpTexture will make myTex be a variable referencing lookedUpTexture.

But how would I do the same for something allocated on the stack? Like an int or a rect?
Lets say I am accessing an int through a chain of 10 address lookups.
How would I go:
int myInt = what.what.what.what.what.what.lookedUpInt
and then have myInt be a reference to lookedUpInt, and not just a copy of it?

What’s your use-case that you’d want a reference of an int?

You could simply wrap it in an object… but I’m starting to suspect there maybe some issues here…

To pass a value type variable by reference the only way is to write a function that uses the out or ref keywords.

Example:

void ProcessInt(ref int variable)
{
variable += 10; // do some stuff here
}

ProcessInt(ref what.what.what.what.what.what.lookedUpInt);