Caching Networking.LocalPlayer
Some programmers like to cache the local player for later use, for instance by adding a private member private VRCPlayerAPI _localPLayer; then setting the local player _localPlayer = Networking.LocalPlayer; in Start()
Let's see how it affects the performance :
public override void Benchmark1()
{
VRCPlayerApi localPlayer = Networking.LocalPlayer;
for (int i = 0; i < 10000; i++)
{
string name = localPlayer.displayName;
}
}
public override void Benchmark2()
{
for (int i = 0; i < 10000; i++)
{
string name = Networking.LocalPlayer.displayName;
}
}
B1 : 15.097 ms
B2 : 18.251 ms (1.20 times slower)
Caching the local player can improve the performance if the local player is used multiple times in the script.
This does not only apply to Networking.LocalPlayer !LocalPlayer! for instance if you need to access the Transform of a particular GameObject it might be interesting to cache the Transform for later use.use:
Transform myTransform;
void Start()
{
myTransform = myGameObject.transform;
}
void Update()
{
//this is more performant than "myGameObject.transform.position"
//especially if the transform is used multiple times, like in this Update()
myTransform.position = newPosition;
}