You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ArrayList元素交换:Collections.swap()与临时变量法哪个效率更高?

Which is More Efficient: Manual ArrayList Swap or Collections.swap()?

Great question! Let’s dig into this to figure out which approach is better, both in terms of efficiency and practicality.

First, Let’s Look at the Underlying Implementations

Let’s start with what each approach actually does under the hood:

Manual Swap

Your manual approach looks like this:

int temp = name.get(0);
name.set(0, name.get(1));
name.set(1, temp);

This involves two explicit get() calls (to fetch both elements) and two set() calls (to overwrite each index with the new value).

Collections.swap()

The standard library’s Collections.swap() method (simplified from OpenJDK source) uses a smarter one-liner:

public static void swap(List<?> list, int i, int j) {
    final List l = list;
    l.set(i, l.set(j, l.get(i)));
}

Here, it leverages the fact that List.set() returns the old value at the index. So it:

  1. Fetches the element at index i
  2. Sets index j to that element, capturing the old value of j in the process
  3. Sets index i to the captured old value of j

Efficiency Breakdown

Let’s count the underlying array operations (since ArrayList uses an array internally):

  • Manual swap: 2 get() calls (each reads one array element) + 2 set() calls (each reads the old element and writes the new one) = 6 total array operations.
  • Collections.swap: 1 get() call + 2 set() calls (each with a read and write) = 5 total array operations.

Technically, Collections.swap() saves one array read operation. But here’s the key point: this difference is negligible for almost all real-world scenarios. The JVM optimizes these low-level operations heavily, and unless you’re swapping elements millions of times in a tight loop, you’ll never notice a performance gap.

Practicality and Readability

Where Collections.swap() truly stands out is in code quality:

  • Conciseness: It’s a single line that immediately communicates your intent, whereas the manual approach requires three lines that force readers to parse the swap logic.
  • Type safety: For generic ArrayLists (e.g., ArrayList<String>), the manual approach requires you to handle the temp variable’s type correctly. Collections.swap() handles generics seamlessly, eliminating the risk of type errors.
  • Flexibility: It works with any List implementation (LinkedList, Vector, etc.), not just ArrayList. If you ever switch your list type later, you won’t have to rewrite the swap logic.
  • Proven reliability: This is a well-tested standard library method used by millions of developers. You don’t have to worry about off-by-one errors or other bugs that could creep into manual swap code.

Final Recommendation

If you’re chasing absolute micro-optimization for a performance-critical loop, Collections.swap() is slightly more efficient. But for 99% of cases, prioritize Collections.swap() for its readability, safety, and flexibility. The tiny performance difference is not worth sacrificing clean, maintainable code.

内容的提问来源于stack exchange,提问作者daswagarv

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 23:07:44