jump-table

Is 'switch' faster than 'if'?

本小妞迷上赌 提交于 2019-11-26 06:11:21
问题 Is a switch statement actually faster than an if statement? I ran the code below on Visual Studio 2010\'s x64 C++ compiler with the /Ox flag: #include <stdlib.h> #include <stdio.h> #include <time.h> #define MAX_COUNT (1 << 29) size_t counter = 0; size_t testSwitch() { clock_t start = clock(); size_t i; for (i = 0; i < MAX_COUNT; i++) { switch (counter % 4 + 1) { case 1: counter += 4; break; case 2: counter += 3; break; case 3: counter += 2; break; case 4: counter += 1; break; } } return 1000