I am wondering if I may optimize something if I change the "huge" numbers by some offsets (or something similar) in the switch-case
statements. So I have done a test :
#include <iostream>
#include <iomanip>
#include <chrono>
int main() {
uint32_t f = 0x12345688;
std::chrono::time_point<std::chrono::system_clock> start, end;
int i = -1;
start = std::chrono::system_clock::now();
switch (f)
{
case 0x1234500 : i = 0; break;
case 0x1234522 : i = 2; break;
case 0x1234555 : i = 5; break;
case 0x1234588 : i = 8; break;
default : break;
}
end = std::chrono::system_clock::now();
std::chrono::duration<double> elapsed_seconds = end-start;
std::cout << "elapsed time: " << elapsed_seconds.count() << "s\n";
int j = -1;
start = std::chrono::system_clock::now();
switch (f & 0xf)
{
case (0x1234500 & 0xf) : j = 0; break;
case (0x1234522 & 0xf) : j = 2; break;
case (0x1234555 & 0xf) : j = 5; break;
case (0x1234588 & 0xf) : j = 8; break;
default : break;
}
end = std::chrono::system_clock::now();
elapsed_seconds = end-start;
std::cout << "elapsed time: " << elapsed_seconds.count() << "s\n";
return 0;
}
and it seems that always the second switch-case is faster.
Is there a reason why the small numbers in the cases is making the statement faster (the "gaps" between the cases are the same)?