检查布尔值比在java中设置布尔值更快? [英] is checking a boolean faster than setting a boolean in java?

查看:205
本文介绍了检查布尔值比在java中设置布尔值更快?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这:

if (var) {
    var = false;
}

对此:

var = false;

是否存在速度差异?

推荐答案

有几件事情发挥作用,对实际性能的最终影响是您需要根据用例来衡量的。我假设这是你发现的一种方法很多:

Several things come into play, ultimate effect on actual performance is something you will need to measure for your use case. I assume this is a method you have found to happen A LOT:


  1. 分支预测 - 如果var几乎总是假的,代码建议的是,分支预测器几乎总是正确的。如果该字段经常更改,那么这将成为一个经常被错误预测的分支并且将是昂贵的。

  1. Branch prediction - if var is almost always false, which is what the code suggests, the branch predictor will be almost always right. If the field changes often then this is will become an often mispredicted branch and will be expensive.

读取未命中 - 如果var主要是读取(并且读取很多)然后避免无故更改可以通过不使其所在的缓存行无效来帮助您的软件。如果你写它的每个其他核心读取它(以及同一缓存行上的任何内容)将需要获得一个新的副本遇到读取错过。这意味着为了使读取速度更加一致,上述方法可能更慢。

Read miss - If var is mostly read (and read A LOT) then avoiding changing without cause can help your software by not invalidating the cache line it sits on. If you write to it every other core who reads it (and anything on the same cache line) will need to get a fresh copy experiencing a read miss. This means the above method may be worth making slower for the sake of making reads have more consistent speed.

写入成本与读取成本 - 如果var是易变的那么它的写入是一个非常昂贵的LoadStore屏障。相比之下,读取volatile(一个LoadLoad屏障)相当便宜(对于经常使用且几乎没有改变的值的缓存命中)。相比之下,这可以使分支非常便宜。

Write cost vs. read cost - if var is volatile then it's write is a LoadStore barrier which is quite expensive. Reading a volatile (a LoadLoad barrier) is rather cheap by comparison (a cache hit for an often used and hardly changed value). This can make the branch very cheap by comparison.

这是人们所做的优化,例子可以在JDK(IIRC),我认为你有理由考虑它。

This is an optimization people make, and examples can be found in the JDK (IIRC), I assume you have a reason to consider it.

这篇关于检查布尔值比在java中设置布尔值更快?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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