Download

Using a switch case vs array with pointers..

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.


int32* ABaseCharacterClass::GetUnitStatPointer(EUnitStat UnitStat) const
{
	return UnitStatsPointerArray(uint8)UnitStat];
}

I wanted to know which using this be more efficient compared to switch case?

Hi envenger,
have you thought about a TMap? That could save you a lot of code in both initialization and pointer’s management.

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.

I smell premature optimization…

This!

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.

I think Arrays are slightly better compared to Map for performance.

From the design perspective, its slightly easier for me to write the code using Arrays…
Easy to call them using Enums…

Hm… Guess I need to stop making premature optimizations.