?: Operator Vs. If Statement Performance

后端 未结 7 852
轻奢々
轻奢々 2020-12-05 23:18

I\'ve been trying to optimize my code to make it a little more concise and readable and was hoping I wasn\'t causing poorer performance from doing it. I think my changes mi

7条回答
  •  盖世英雄少女心
    2020-12-05 23:43

    For discussion sake... if/then/else runs just as fast as the ?: ternary operation as fast as a single level switch/case statement.

    Here are some performance benchmarks with the C# code.

    It's only when you start getting 2-3 levels deep in case statements that performance starts to be severely impacted. That is, something like this ridiculous example:

    switch (x % 3)
        {
            case 0:
                switch (y % 3)
                {
                    case 0: total += 3;
                        break;
                    case 1: total += 2;
                        break;
                    case 2: total += 1;
                        break;
                    default: total += 0;
                        break;
                }
                break;
            case 1:
                switch (y % 3)
                {
                    case 0: total += 3;
                        break;
                    case 1: total += 2;
                        break;
                    case 2: total += 1;
                        break;
                    default: total += 0;
                        break;
                }
                break;
        case 2:
                switch (y % 3)
                {
                    case 0: total += 3;
                        break;
                    case 1: total += 2;
                        break;
                    case 2: total += 1;
                        break;
                    default: total += 0;
                        break;
                }
                break;
        default:
            switch (y % 3)
            {
                case 0: total += 3;
                    break;
                case 1: total += 2;
                    break;
                case 2: total += 1;
                    break;
                default: total += 0;
                    break;
            }
            break;
        }
    

提交回复
热议问题