覆盖与查找
我正在阅读 android 中的 SparseArray
类,并遇到了以下方法:
public void removeAt(int index) {
if (mValues[index] != DELETED) {
mValues[index] = DELETED;
mGarbage = true;
}
}
显然这也可以被编写:
public void removeAt(int index) { Or public void removeAt(int index) {
if (mValues[index] != DELETED) { mValues[index] = DELETED;
mValues[index] = DELETED; mGarbage = true;
if (!mGarbage) }
mGarbage = true;
}
}
看起来 android 开发人员相信数组查找 mValues[index]
比数组写入快,但变量查找并不比变量写入快。
这是真的吗?它取决于VM,还是编译语言中的常识?
I was reading through the SparseArray
class in android, and came across the following method:
public void removeAt(int index) {
if (mValues[index] != DELETED) {
mValues[index] = DELETED;
mGarbage = true;
}
}
Clearly this could as well has been written:
public void removeAt(int index) { Or public void removeAt(int index) {
if (mValues[index] != DELETED) { mValues[index] = DELETED;
mValues[index] = DELETED; mGarbage = true;
if (!mGarbage) }
mGarbage = true;
}
}
It would seem the android developers believed the array lookup mValues[index]
was faster than an array write, but the variable lookup wasn't faster than a variable write.
Is this really true? Does it depend on the VM, or is it general knowledge in compiled languages too?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
当然,右侧版本不等效 - 因为无论值是否已更改,
mGarbage
都会设置为 true。左边和原来的一样,但是没有意义。
基本上,我认为您错过了检查现有值是否允许 DELETED 的副作用:它允许
mGarbage
设置为 true 仅如果该方法具有确实有效果。这与从数组读取的性能无关。Certainly the right-hand side version is not equivalent - because then
mGarbage
is set to true whether or not the value has changed.The left-hand side is equivalent to the original, but it's pointless.
Basically I think you've missed the side-effect of checking whether or not the existing value was allows DELETED: it allows
mGarbage
to be set to true only if the method has actually had an effect. That has nothing to do with the performance of reading from the array.这在很大程度上取决于虚拟机,我猜想这个特定的代码是针对 Dalvik 虚拟机进行调整的(或者它只是 Apache Harmony 碰巧实现的任何代码)。
要记住的一件事是,写入总是意味着一些与缓存和跨线程交互相关的成本(即,您可能需要内存屏障才能正常工作),而读取则更容易执行。
It depends a lot on the VM and I'd guess that this specific code is tuned for the Dalvik VM (or it's just whatever Apache Harmony happened to implement).
One thing to remember is that a write always implies some cost related to caching and cross-thread interaction (i.e. you might need memory barriers for it to work correctly), while a read is much easier to do.
这个假设可能是正确的,尽管它在很大程度上取决于处理器和 JVM 实现。
一般原因与数组和变量关系不大,而与内存访问模式关系更大:
The assumption is probably true, although it will depend a lot on the processor and JVM implementation.
The general reason is less to do with arrays vs. variables but more to do with memory access patterns: