BuringStraw

BuringStraw

Useless card constant experiment

Useless Card Constant Experiment#

I remembered someone saying that the ternary operator is slower than if-else,

and someone else said that adding inline actually makes it slower.

So, let's do an experiment.

(I'm embarrassed to even put up such a stupid experiment)

Preparation#

  • "Functions" written in three ways. Because I'm too lazy, I used the simplest max

    #define max(a, b) ((a) > (b) ? (a) : (b))
    
    int max (int a, int b) {
    	if (a > b) return a;
    	else return b;
    }
    
    int max (int a, int b) {
    	return ((a) > (b) ? (a) : (b));
    }
    

    The last two were tested with and without inline

  • Main program

    Using rand() without srand() to generate data, so it's not only randomly distributed, but the total data is the same

    int main (void) {
    	for (int i = 1; i <= 100000000; ++i) {
    		int x = rand(), y = rand();
    		int z = max(x, y);
    	}
    	return 0;
    }
    
  • Calculatorutools is really useful

Process#

Following the principles of scientific experiments, each test was done five times, and the average value was taken.

Results#

From top to bottom: define, if without inline, if with inline, ternary without inline, ternary with inline

UTOOLS1572873241403.png

Conclusion#

define is very fast, use it as much as possible.

The ternary operator is faster than if-else.

inline is faster than without inline.
。。。。。。。。。。。。
It seems like there isn't much difference

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.