Search code examples
javalistpass-by-referencepass-by-value

Adding to a List by Value instead of reference in Java


I have a list of maps and in a for-loop I want to add a Map to the list. I heard that using map.clear() has a better performance than creating a new Map but my problem is that List.add() works with the reference of the object and by using Map.clear() the reference is not ceared.

Is there a possibility to force List.add() to use the value or to build an other workaround?


Solution

  • It is possible to insert "by value" by simply creating a copy of the Map and inserting the copy. The problem with this is that it's not an optimization at all.

    Instead of simply creating a new empty Map, you create a copy of a filled Map and clear the original Map. This means: you don't avoid the overhead of creating a new Object, but also introduce the extra work of copying and clearing a filled Map.

    And a little note on optimization in general:
    It's ~10% of your code that'll be doing 90% of the work (yes, these numbers are made up, but it's the usual way to think about optimization and at least close to reality). Don't over-optimize your code in the first run. Just do what can be done easily and without making the code less readable, run a profiler and look for the bottlenecks of your code and optimize those. This is by far more efficient and easier than optimizing the entire code.