Given the following code snippet in which an ad hoc instance of a Set
is created, will todays Java compiler see that they do not need to create the instance for each loop pass and optimize set
as a kind of final constant such that the instance is the same for the entire loop? The question applies similarly to while
and do while
loops.
for (/* a loop that iterates quite often */)
{
var set = Set.of("foo", "blah", "baz");
// Do something with the set.
}
I would also be interested whether such an optimization is done already at compile-time (meaning that the byte code is already optimized) or whether there exist runtime optimizations (made by the just-in-time compiler) that essentially achieve the same.
If a compiler does not see this, the only option seems to instantiate the set
outside the loop in order to be optimal:
var set = Set.of("foo", "blah", "baz");
for (/* a loop that iterates quite often */)
{
// Do something with the set.
}
Side note, for those finding the first snippet rather bad practice and that would write it like the second snippet anyway: This snippet is actually a simplified variant of my real use case, made for simplicity reasons of the question. The real, slightly more complex use case that brought me to this question is the following, where a string needs to be checked whether it is one of a very few strings:
for (/* a loop that iterates quite often */)
{
// ...
var testString = // some String to check ...
if (Set.of("foo", "blah", "baz").contains(testString))
{
// Do something.
}
// ...
}
Assuming that the if
condition is surrounded by additional code (i.e., the loop body is rather large), I think one wants to declare the set inline rather than further away outside the loop.