Lennard Fonteijn Lennard Fonteijn - 2 months ago 8
C# Question

Java For Each with a getter

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());

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
in a temporary variable before iterating over it. But if not, I have no trouble helping the compiler a hand :P


The compiler will store the iterator (from calling the iterator() method on the Iterable) that it loops over, so the getPlayers() method will only be called once. You could observe this using the below adaption of getPlayers()

public Iterable<Player> getPlayers() {
    System.out.println("getPlayers() called");
    return Collections.unmodifiableList(this.players);

When running your first code snippet, "gePlayers() called" would only be printed once.

Check the Iterable docs for more detail (notable the iterator() method): https://docs.oracle.com/javase/8/docs/api/java/lang/Iterable.html