Hello everyone!
I just wanted to ask if it could be useful to store data in script A after accessing it from script B?
Or is accessing other scripts “free” (performance-wise)?
For example:
Script A:
public B b;
string someString;
void Something () {
someString = b.someString;
if (someString == "something1") {}
else if (someString == "something2") {}
else if (someString == "something3") {}
else if (someString == "something4") {}
else if (someString == "something5") {}
}
Script B:
public string someString;
Greetings,
Shu
Accessing other scripts is basically free; copying a string is almost certainly slower.
Your chain of if-else statements would be a bigger problem. If you have a bunch of strings to compare against, a switch statement is probably faster. This discussion on SO describes why: essentially, for large amounts of code, it compiles a Dictionary-like construct, and Dictionary lookups are very fast. Added bonus: the switch statement would only access b.someString once, so you’d get the benefits of caching the string (if there are any) without the cost of having to copy it.
That said, all of this is going to be in tiny, tiny fractions of a millisecond even with hundreds of instances. Don’t pre-optimize! Run the profiler, and see where your real performance hogs are!
1 Like
@StarManta
Thanks a lot for your detailed answer! Very informative!
I just wanted to make sure because I wasn’t aware of how C# is going to be changed later on.
But when reading your explanation, it sounds reasonable to just ignore it until it might become an issue at some point, if possible at all!