In the code below, I needed to get an element, any element, from toSearch. I could not find a useful method for defining the definition of Set to return only one (random, but not necessarily random) element of the set. So, I used the toArray () [0] technique (presented in the code below).
private Set<Coordinate> floodFill(Value value, Coordinate coordinateStart) { Set<Coordinate> result = new LinkedHashSet<Coordinate>(); Set<Coordinate> toSearch = new LinkedHashSet<Coordinate>(); toSearch.add(coordinateStart); while (toSearch.size() > 0) { Coordinate coordinate = (Coordinate)toSearch.toArray()[0]; result.add(coordinate); toSearch.remove(coordinate); for (Coordinate coordinateAdjacent: getAdjacentCoordinates(coordinate)) { if (this.query.getCoordinateValue(coordinateAdjacent) == value) { if (!result.contains(coordinateAdjacent)) { toSearch.add(coordinateAdjacent); } } } } return result; }
Another way I've seen is to replace " (Coordinate) toSearch.toArray () [0] " with " toSearch.iterator (). Next () ". Which technique, toArray () or iterator (), is most likely to run most quickly with minimal GC (Garbage Collection) effect?
My intuition (after compiling this question) is that the second method using Iterator will both execute faster and reduce overhead for GC. Given that I don’t know the implementation of the passed set (suppose that a HashSet or LinkedHashSet is most likely), how much overhead comes from each of the toArray () or iterator () methods? Any ideas on this would be greatly appreciated.
Questions (repeated from above):
- Which method, toArray () or iterator (), is most likely to perform the fastest actions with minimal impact of GC (Garbage Collection)?
- Given that I do not know the implementation of the transferred set (suppose that a HashSet or LinkedHashSet is most likely), how much overhead is incurred in each of the toArray () and iterator () methods?
java performance iterator set toarray
chaotic3quilibrium
source share