Home > Software design >  Will adding a sequence of consecutive numbers after a sequence of ordered, but non-consecutive numbe
Will adding a sequence of consecutive numbers after a sequence of ordered, but non-consecutive numbe

Time:10-31

I have a switch which has some random numbers: 1,5,16...
Imagine there are 10 or 20 of them.
After them, I have some macros where I can assign my own signed int numbers. So they can be 1000, or 32000...
Imagine there are also 10 or 20 of those.

Now, my question is:

  • will ordering and making my numbers consecutive even help with optimization if the former numbers are ordered but not consecutive?
  • will using smaller numbers (like 1000, compared to 32000) affect performance in any theoretical way?

Code:

switch (x) {
    case 1:
    // stuff
    break; 

    case 5:
    // stuff
    break;

    case 16:
    // stuff
    break;

    case 32000:
    // stuff
    break;

    case 32001:
    // stuff
    break;

    case 32002:
    // stuff
    break;

    defult:
    break;
}

If you need hardware specifics, imagine we are talking about the most default theoretical scenario: gcc, intel, no optimizations.

Please advise.

CodePudding user response:

That depends on your compiler, usually it should not help. Some compiler may implement a binary search, others may implement a if/else chain. But as long as not all of your numbers are consecutive there won't be a jump table*. The order of your case statements does not make a difference.

switch (x) {
case 1:
     ...
     break;
case 3:
     ...
     break;
case 5:
     ...
     break;
}

and

switch (x) {
case 1:
     ...
     break;
case 5:
     ...
     break;
case 3:
     ...
     break;
}

Will be (usually) compiled to exactly the same code.

EDIT:

If larger numbers than the type of x can handle, the result is undefined. Otherwise it does not make a difference.

*Sometimes it can be worth, for example if there are just gaps between the numbers.

  •  Tags:  
  • c
  • Related