assuming I have defined a HashSet<String> set.
What is better in terms of performance:
set.clear;
or
set = new HashSet<String>();
EDIT: the reason I am checking this is that currently my code has the second option, but I want to change it to the first one to make the Set final.
Although
clearmight be more performant, this depends on the size of the set. In practice, this is not likely to make a significant difference in the performance of your application. Even in the limited scope of lines of code around this function, performance will be dominated by other factors such as JIT compilation.What is important is design quality, which will make it easy to refactor for performance after you have profiled your code. In most cases, avoiding hard-to-track state changes is important, and creating a new
HashSetis better design than reuse of aHashSet.