Java – speedup HashSet and HashMap performance
In Java, I have:
Set<Integer> set = new HashSet<Integer>(); callVoidMethod(set); ... public static void callVoidMethod(Set<Integer> set) { Set<Integer> superset = new HashSet<Integer>(set); ... // I just added this loop to show that I'm adding quite a lot // well,it depends on conditions,sometimes I add nothing,// but it is unpredictable and do not kNow if add something for (int i = 0; i < 1000; i++) { ... if (conditionSatisfied) superset.add(someValue); ... } }
The above code is simplified. The idea is to pass the collection to the void method by reference and create a complete copy of the collection, so that we can add some new elements to the copy (superset in this case) and don't touch the setting that we don't need it when we exit the void method
My code is applicable to a large amount of data processing. If there is no faster way to make copies, I want to optimize the HashSet itself. For example, I don't need integers as a key, but a better original int. is it a good idea to implement an int [] array in myhashset?
If possible, I would be interested in using the same idea to improve this:
Map<Integer,ArrayList<Item>> map = new HashMap<Integer,ArrayList<Item>>();
Editor: I just need speed performance optimization I don't need beautiful maintainable code and memory
Solution
How do you deal with these objects in the future? If you're just doing a search or something like that, it might be faster to separate them and check them instead of making a full copy So,
public static void callVoidMethod(Set<Integer> set) { Set<Integer> superset = new HashSet<Integer>(); ... if (conditionSatisfied) superset.add(someValue); ... if(set.contains(value) || superset.contains(value)) doSomething(); }