It's been a while since I last used Java, as I'm primarily a C# developer. To get back into the game, I was working on a very simple application to touch on most of the key features of the language. I ran across the following problem:
for (Player player : teamRed.getPlayers()) {
System.out.format("> %s\n", player.getName());
}
Where getPlayers()
is defined as follows:
public Iterable<Player> getPlayers() {
return Collections.unmodifiableList(this.players);
}
At some point in the past, either C# or Java had a performance issue when you used a getter in your for each like this, as it would execute the method every iteration. I cannot find anything about this anymore, so I wonder:
Has Java ever been subject to this issue, or was it the case for C# only?
Personally, I feel the compiler should be smart enough to optimize this properly and actually store the result of getPlayers
in a temporary variable before iterating over it. But if not, I have no trouble helping the compiler a hand :P