I am trying to get the value of a variable by passing an enum.
There are around 30 variables so 30 switch cases which I don’t think might be that efficient considering I have to call it regularly and for all clients.
So I thought instead of using a switch case, I could store the pointer of all those variables in an array in the same order as which the enum was declared.
And get the pointer to the value with something like this.
First: “I think it might not be efficient” in a small case can only be proven with a profile. Run a profiler on both cases, and select the fastest, if you think this will actually matter.
Second: The compiler is very good. It will actually generate a jump table (similar to an array of function pointers, but less overhead) if the switch statement would run faster that way. Note that indirect jumps are bad for branch prediction, and large tables are bad for cache, so it’s not a 100% given that the array-of-pointers will be any faster at runtime.
Third: Often when you build a switch statement, you really actually want a virtual function in some interface/class instead.
Switches will be fine for 30 objects. It’s when you get into the 1000’s that you’ll have problems, and a performance benefit can be truly gained. Even then you’ll have to profile though. Branch Prediction probably favours switches to be honest.