• Welcome to TechPowerUp Forums, Guest! Please check out our forum guidelines for info related to our community.

Switch or array? (C)

Joined
Feb 18, 2010
Messages
1,850 (0.36/day)
System Name Eldritch
Processor AMD Ryzen 5 5800X3D
Motherboard ASUS TUF X570 Pro Wifi
Cooling Satan's butthole after going to Taco Bell
Memory 64 GB G.Skill TridentZ
Video Card(s) Vega 56
Storage 6*8TB Western Digital Blues in RAID 6, 2*512 GB Samsung 960 Pros
Display(s) Acer CB281HK
Case Phanteks Enthoo Pro PH-ES614P_BK
Audio Device(s) ASUS Xonar DX
Power Supply EVGA Supernova 750 G2
Mouse Razer Viper 8K
Software Debian Bullseye
Say I have a little bit of code. Let's say it's something along the lines of:
Code:
unsigned int find_length_of_magnitude(unsigned int magnitude)
{
    unsigned float half = magnitude/2.0f;//Needed?
    unsigned int answer = 1+(6*(half*(magnitude-1)));//Put in return line?
    return answer;
};

Now let's say I want to put in a little (OK, maybe it's big) look-up table, and let's say I don't give a crap about code size (unless it would cause actual problems). Now would a switch table be faster than an array (being pointed to)? Or would a fatty switch table just be useless bloat and bullshit?
 

W1zzard

Administrator
Staff member
Joined
May 14, 2004
Messages
27,049 (3.71/day)
Processor Ryzen 7 5700X
Memory 48 GB
Video Card(s) RTX 4080
Storage 2x HDD RAID 1, 3x M.2 NVMe
Display(s) 30" 2560x1600 + 19" 1280x1024
Software Windows 10 64-bit
execution time of your code is basically zero. no point writing a lookup table for that.

in general, lookup tables are good, if you can calculate the key into your table quickly.

internally a switch statement often ends up being a lookup into an array with jump adresses (so that's already as expensive as your look up table)

write readable code, let the compiler's optimizer do the work. it's usually smarter than the programmer.
 
Joined
Feb 18, 2010
Messages
1,850 (0.36/day)
System Name Eldritch
Processor AMD Ryzen 5 5800X3D
Motherboard ASUS TUF X570 Pro Wifi
Cooling Satan's butthole after going to Taco Bell
Memory 64 GB G.Skill TridentZ
Video Card(s) Vega 56
Storage 6*8TB Western Digital Blues in RAID 6, 2*512 GB Samsung 960 Pros
Display(s) Acer CB281HK
Case Phanteks Enthoo Pro PH-ES614P_BK
Audio Device(s) ASUS Xonar DX
Power Supply EVGA Supernova 750 G2
Mouse Razer Viper 8K
Software Debian Bullseye
Yeah, that's what I figured.
 
Top