ave4496
ave4496

Reputation: 3028

Does code in methods always get executed?

I have created the implementation of a abstract method of the super class. Does the code in the method always get executed or is there some kind of cache that knows the code will never change?

I want to know if there are performance issues with my code. Is it better to create the map as a member variable and then return it in the method?

@Override
protected Map<String, Function<Information, String>> getDefinitionMap() {
    final Map<String, Function<Information, String>> map = new LinkedHashMap<>();
    map.put("Name", t -> t.getName());
    map.put("ID", t -> t.getId());
    return map;
}

Upvotes: 3

Views: 77

Answers (1)

Henry
Henry

Reputation: 43788

Each time the method getDefinitionMap() is called, a new LinkedHashMap instance is created. There is no "implicit caching".

You can avoid that, if you create the map once, store it in a member variable and return this. You may want to make it unmodifiable so that it cannot be changed by callers. (see java.util.Collections.unmodifiableMap)

Upvotes: 4

Related Questions