Writting and reading static variables (performance)

Hi, I was wondering if having several static variables and continually modify and read them is bad in terms of optimization.
I need them to be static because these represent different stats the player has and the stats can be modified by lots of gameObjects and them should be readable by many other scripts as well.

I basically made a public static class:

public static class Stats
{
    public static float accuracy;
    public static float recoil;
    public static float bulletDamage;
    ...... //etc
}

Then I read and modify the variables like this:
Stats.bulletDamage = weapon.bulletDamage;
float damageDealt = Stats.bulletDamage

Is it a good practise to keep modifying and reading them every 4 secs or so? (in terms of performance and garbage and all that)
I know how and when to use static variables but I have no idea how “fast” unity handles them.
Thankss!!

You should not worry about micro-managing performance at this level. If you have a performance issue, you’d be MUCH better served using the Profiler and look at the peaks there. That being said - if you have 101 items that impact performance, it is doubtful that access to static variables will be within the top 100 items of concern.

Cheers,
-ch

Thanks and that’s true. Things are getting bigger and I started worrying lot more on how the code perform but profiler shows everything works well. Thanks again!

Accessing a static field is no different than accessing a member field as performance goes.

A property is slower than a field, or having to locate a reference to an object before accessing its field is slower. But static field vs member field performance is identical since they’re both really the same operation of “read/write address in memory”. It’s just with what the address is associated that differs.

Mind you… there is ‘technically’ a potential latency issue from a data oriented context. But it’s not the fact its static that could cause this. Just how the memory just so happens to be laid out. But if this was your bottleneck… it’s like having a car so well tuned that you could measure the fuel lost by hitting a gnat on the highway at 100mph.

3 Likes

Hahaha I loved that comparison. Actually I don’t have a bottleneck, just wondering if this it is a bad practise or can lead to performance problems in the future. Now I have it clear, many thanks!