Java中数组元素的高效交换 [英] Efficient swapping of elements of an array in Java
问题描述
我想知道是否有比执行以下操作更有效的方法来交换数组中的两个元素:
I am wondering if there is a more efficient way of swapping two elements in an Array, than doing something like this:
String temp = arr[1];
arr[1] = arr[2];
arr[2] = temp;
嗯,这显然不错,甚至是错误的,但我需要经常交换,所以我很感兴趣,如果有任何 Libs 或其他东西可以提供更有效的方法来做到这一点?
Well, this is obviously not bad or even wrong, but I need to swap very often so I am interested if there are any Libs or something that provide a more efficient way to do this?
推荐答案
不.你可以有一个函数来让它在你使用它的每个地方都更简洁,但最终,所做的工作将是相同的(加上函数调用的开销,直到/除非 HotSpot 将它内联移动 - 帮助它, 使函数static final
).
Nope. You could have a function to make it more concise each place you use it, but in the end, the work done would be the same (plus the overhead of the function call, until/unless HotSpot moved it inline — to help it with that, make the function static final
).
这篇关于Java中数组元素的高效交换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!