多少情况下标签的订单影响switch语句的效率? [英] How much does the order of case labels affect the efficiency of switch statements?

查看:130
本文介绍了多少情况下标签的订单影响switch语句的效率?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑:

if (condition1)
{
    // Code block 1
}
else
{
    // Code block 2
}

如果我知道条件1 真正大部分的时间,那么我应该code书面的逻辑,而不是:

If I know that condition1 will be true the majority of the time, then I should code the logic as written, instead of:

if (!condition1)
{
    // Code block 2
}
else
{
    // Code block 1
}

因为我将避免来第二code座的刑罚(注:我有限的了解汇编语言)。难道这个想法发扬开关报表和情况标签?

since I will avoid the penalty of the jump to the second code block (note: I have limited knowledge of assembly language). Does this idea carry forward to switch statements and case labels?

switch (myCaseValue)
{
    case Case1:
        // Code block 1
        break;

    case Case2:
        // Code block 2
        break;

    // etc.
}

如果我知道的情况下,人会更频繁地发生,我可以重新排列情况的顺序标签,这样它的效率更高?我是不是该?在我的code我一直在按字母顺序排序的情况下标签code可读性没有真正思考它。这是微观优化?

If I know that one of the cases will happen more often, can I rearrange the order of the case labels so that it's more efficient? Should I? In my code I've been ordering the case labels alphabetically for code readability without really thinking about it. Is this micro-optimization?

推荐答案

一些事实现代硬件像x86或x86_64的:

Some facts for modern hardware like x86 or x86_64:


  • 一个无条件的分支几乎没有额外的费用,除了解码。如果你想有一个数字,它是大约四分之一时钟周期。

  • 的条件分支,这是正确的predicted,几乎没有额外的费用。

  • 的条件分支,这是不正确的predicted,具有等于处理器管线的长度一个点球,这是12-20个时钟,这取决于硬件。

  • 的prediction机制是非常复杂的。具有低迭代次数(核心2例如多达64个)的循环可以是完全predicted。小重复图案像拍摄,拍摄-nottaken,采取可以是predicted,如果他们不是太长(IIRC 6上酷睿2)。

您可以阅读更多关于瓦格纳雾优秀手动分支prediction。

You can read more about branch prediction in Agner Fogs excellent manual.

开关语句通常由编译器换成了跳表。在大多数情况下,案件的顺序不会使所有的差异。有间接跳转prediction机制以及

Switch statements are usually replaced by a jump table by the compiler. In most cases the order of cases won't make a difference at all. There are prediction mechanisms for indirect jumps as well.

所以,问题不在于你是否跳跃更有可能采取,那是如果他们是很好predictable,至少在硬件要运行在你的code。这不是一个简单的问题都没有。但如果你有依赖于一个随机(或伪随机)的条件分支,你可以尝试改写它作为如果可能的话网点声明。

So the question isn't if your jumps are more likely to be taken, it is if they are well predictable, at least for the hardware you intend to run your code on. This isn't an easy question at all. But if you have branches depending on a random (or pseudo random) condition, you could try to reformulate it as a branchless statement if possible.

这篇关于多少情况下标签的订单影响switch语句的效率?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆