简体   繁体   English

这是Java中整数数组中更昂贵的操作交换或比较

[英]Which is more expensive operation swap or comparison in integer array in Java

Which is more expensive operation swap or comparison in integer array in Java ? 在Java中,哪个是更昂贵的操作交换或整数数组中的比较? Or they can all be thought as same ? 或者他们都可以被认为是一样的?

Context: Sorting for an almost sorted array (I am not talking about k-sorted array where each element is displaced from the right position by at most k). 上下文:对几乎排序的数组进行排序(我不是在谈论k排序的数组,其中每个元素从最右边的位置移位最多k)。 Even if we use insertion sort, number of comparisons by the end will be same as they would have been for any array or for worst case. 即使我们使用插入排序,最终的比较次数也会与任何数组或最坏的情况相同。 Isn't it ? 不是吗? It is just that swaps will be fewer. 只是互换将会减少。 Please correct if I am wrong. 如果我错了,请纠正。

Swap should be more expensive because it includes: 交换应该更昂贵,因为它包括:

  1. Reading data from memory to cache 从内存中读取数据到缓存
  2. Reading data from cache to registers 从缓存读取数据到寄存器
  3. Writing data back to cache 将数据写回缓存

Comparison should be less expensive because it includes: 比较应该更便宜,因为它包括:

  1. Reading data from memory to cache 从内存中读取数据到缓存
  2. Reading data from cache to registers 从缓存读取数据到寄存器
  3. Executing single compare operations on two registers (which should be a little faster than writing two integers into a cache) 在两个寄存器上执行单个比较操作(这应该比将两个整数写入缓存快一点)

But modern processors are complex and different from each other, so the best way to get the right answer is to benchmark your code. 但现代处理器很复杂且彼此不同,因此获得正确答案的最佳方法是对代码进行基准测试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM