【发布时间】:2015-04-03 18:00:00
【问题描述】:
选项1:
boolean isFirst = true;
for (CardType cardType : cardTypes) {
if (!isFirst) {
descriptionBuilder.append(" or ");
} else {
isFirst = false;
}
//other code not relevant to this theoretical question
}
选项2:
boolean isFirst = true;
for (CardType cardType : cardTypes) {
if (!isFirst) {
descriptionBuilder.append(" or ");
}
isFirst = false;
//other code not relevant to this theoretical question
}
我的分析:两段代码语义相同。
第一个代码)我不确定这段代码是有两个分支(就分支预测器而言)还是一个分支。我正在研究http://en.wikipedia.org/wiki/X86_instruction_listings,但无法弄清楚是否存在类似于“如果先前的条件值是假的跳转那里”之类的 X86 指令,以避免两个分支预测(非常糟糕)
第二个代码)最有可能总是执行简单的 MOV(寄存器或元素很可能已经在缓存中),这是相对便宜的(最多几个周期)
所以,我的观点是,除非处理器解码成微码指令可以做一些智能的事情或存在 X86 指令以避免必要的分支预测,否则第二个代码会更快。
我知道这纯粹是理论上的问题,因为在实践中,这个分支可以使应用程序快 0.000000002% 或类似的东西。
我错过了什么吗?
编辑:我添加了一个循环,为相关分支提供更多“权重”
EDIT2:问题是关于分支预测的英特尔架构(奔腾和更新的处理器)。
【问题讨论】:
标签: java assembly compiler-construction branch-prediction vm-implementation