-1

I used java for a while. But always have a question as below. Let's say I have a Result class

public class Result {

     private List<Entity1> entity1List;
     private Map<String, Entity2> entity2Map;
     private Map<Integer, Entity3> entity3Map;

     ......
}

Now I have method to use the inside results of this class. Which way is more efficient?

Way 1:

public void test1 (Result result, List<User> users) {
      Map<String, Entity2> entity2Map = result.getEntity2Map();
      for (User user : users) {
           System.out.println(entity2Map.get(user.getUID()));
      }
} 

Way 2:

public void test1 (Result result, List<User> users) {
      for (User user : users) {
          System.out.println(result.getEntity2Map().get(user.getUID()));
      }
} 

Which way is more efficient? Or they are the same? Thanks.

Laodao
  • 1,547
  • 3
  • 17
  • 39

1 Answers1

1

This is more of a question about what the compiler will do and depends on what the method .getEntity2Map() does.

If the method is just returning a reference without doing anything else, then the compiler may notice that and will make Way 1 out of Way 2. You can check whatever the compiler did by decompiling the class file. Here is a question on SO about the how.

In general, it's probably better to use Way 1 because you explicitly create a temporary variable. If the method .getEntity2Map() is called again and again and the compiler doesn't optimize that, a new stack frame is created for each call. Each creation of a stack frame takes time; if the result of the method doesn't change anyways, this is wasted time.

akuzminykh
  • 4,522
  • 4
  • 15
  • 36