Java中整数数组中哪个更昂贵的操作交换或比较 [英] Which is more expensive operation swap or comparison in integer array in Java

查看:45
本文介绍了Java中整数数组中哪个更昂贵的操作交换或比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Java 中整数数组中哪个更昂贵的操作交换或比较?或者他们都可以被认为是一样的?

Which is more expensive operation swap or comparison in integer array in Java ? Or they can all be thought as same ?

上下文:对几乎已排序的数组进行排序(我不是在谈论 k 排序数组,其中每个元素从正确位置最多偏移 k).即使我们使用插入排序,最后的比较次数也将与任何数组或最坏情况下的比较次数相同.不是吗?只是掉期会更少.如果我错了,请纠正.

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). 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 应该更贵,因为它包括:

Swap should be more expensive because it includes:

  1. 从内存读取数据到缓存
  2. 从缓存中读取数据到寄存器
  3. 将数据写回缓存

比较应该更便宜,因为它包括:

Comparison should be less expensive because it includes:

  1. 从内存读取数据到缓存
  2. 从缓存中读取数据到寄存器
  3. 对两个寄存器执行单个比较操作(这应该比将两个整数写入缓存快一点)

但是现代处理器很复杂并且彼此不同,因此获得正确答案的最佳方法是对您的代码进行基准测试.

But modern processors are complex and different from each other, so the best way to get the right answer is to benchmark your code.

这篇关于Java中整数数组中哪个更昂贵的操作交换或比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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