Switch statement with huge number of cases

前端 未结 4 691
有刺的猬
有刺的猬 2021-02-14 06:08

What happens if the switch has more than 5000 case. What are the drawbacks and how we can replace it with something faster?

Note: I am not expe

4条回答
  •  迷失自我
    2021-02-14 07:01

    Big switch statement, generally auto-generated one, may take long time to compile. But I like the idea that compiler optimizes the switch statement.

    One way to break apart the switch statement is to use bucketing,

    int getIt(int input)
    {
      int bucket = input%16;
      switch(bucket)
      {
        case 1:
          return getItBucket1(input);
        case 2:
          return getItBucket2(input);
        ...
        ...
      }
      return -1;
    }
    

    So in the code above, we broke apart our switch statement into 16 parts. It is easy to change the number of buckets in auto-generated code.

    This code has added run-time cost of one layer of indirection or function-call. . But considering the buckets defined in different files, it is faster to compile them in parallel.

提交回复
热议问题