Search code examples
javaarraylistcollectionstime-complexityswap

Which is more efficient for array lists: collections.swap() or using a temporary variable to swap?


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

Collections.swap(name, 0, 1)

I want to swap two elements and don't know which is more efficient. It seems like the runtime of both swaps are the same but I'm not too sure. Thanks!


Solution

  • I want to swap two elements and don't know which is more efficient. It seems like the runtime of both swaps are the same but I'm not too sure.

    The only way to be sure is to write a proper micro-benchmark, run it (on a number of hardware platforms / Java versions) and interpret the results.

    We can look at the source code, and make some informed guesses, but we cannot deduce micro-level efficiency from first principles1.

    My advice:

    • Write the code in the way that you think is most readable, and let the compilers do the optimization. They can typically do a better job than most programmers.
    • If performance of your application is a concern, then write an application benchmark and use a profiler to find out where the real performance hotspots are.
    • Use the hotspot information to decide where it is worthwhile expending effort in hand-tuning the application ... not your intuition / guesswork.

    1 - ... unless there is someone here with an unhealthily detailed amount of knowledge in their heads about how real world Java JIT compilers actually work across multiple platforms. And if there is someone here like that, we should probably just let them rest quietly, rather than bugging them with questions like this :-)