如何在索引肯定在范围内时避免边界检查?

huangapple go评论76阅读模式
英文:

How to avoid bounding check when index is surely in range?

问题

我发现像这样的代码仍然会触发边界检查(通过添加-gcflags="-d=ssa/check_bce/debug=1"):

// 在其他地方保证切片非空

idx := someUintVariable % len(slice)

slice[idx] = someValue // 发现 IsInBounds 错误,如何避免?

在这种情况下,有没有办法强制编译器不进行边界检查?

英文:

I found code like this will still trigger bounding check(by adding -gcflags="-d=ssa/check_bce/debug=1"):

// slice is guaranteed to be non empty elsewhere

idx := someUintVariable % len(slice)

slice[idx] = someValue // Found IsInBounds, how to avoid that?

Is there a way to force the compiler not to do bounding check in this case?

答案1

得分: 2

在这种情况下,有没有一种方法可以强制编译器不进行边界检查?

只有通过使用gcflags=-B来禁用所有边界检查。

没有一个"内联标志"可以仅在单个情况下关闭边界检查。

请注意,编译器有时可以自行证明边界检查不会失败,从而跳过边界检查。由于这是一个不断发展的实现细节,没有可靠的方法来触发这一点。

英文:

> Is there a way to force the compiler not to do bounding check in this case?

Only by disabling all bound checks with gcflags=-B.

There is no "inline flag" to turn off bound checking in just a single case.

Note that the compiler sometimes can prove to itself that the bound check cannot fail and thus drops the bound check. There is no reliable way to trigger this as this is an evolving implementation detail.

huangapple
  • 本文由 发表于 2022年9月23日 10:20:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/73822382.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定