英文:
which one is more efficient? Declare an object for the temp result of a map's values? Or directly fetch from the map root?
问题
以下是翻译好的部分:
我之前使用过一段时间的Java。但是一直有一个以下的问题。假设我有一个名为 Result 的类。
public class Result {
private List<Entity1> entity1List;
private Map<String, Entity2> entity2Map;
private Map<Integer, Entity3> entity3Map;
// ......
}
现在我有一个方法要使用这个类内部的结果。哪种方式更有效呢?
方式 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()));
}
}
方式 2:
public void test1(Result result, List<User> users) {
for (User user : users) {
System.out.println(result.getEntity2Map().get(user.getUID()));
}
}
哪种方式更有效?或者它们是相同的吗?谢谢。
英文:
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.
答案1
得分: 1
这更像是关于编译器行为的问题,取决于方法.getEntity2Map()
的具体实现。
如果该方法只是返回一个引用而没有执行其他操作,那么编译器可能会注意到这一点,并将Way 1优化为Way 2。您可以通过对class
文件进行反编译来查看编译器的优化情况。这里是一个关于此的栈内问题。
一般来说,最好使用Way 1,因为您会显式地创建一个临时变量。如果方法.getEntity2Map()
被反复调用,而编译器没有进行优化,那么每次调用都会创建一个新的堆栈帧。每次堆栈帧的创建都需要时间;如果方法的结果始终不会改变,那么这将是浪费的时间。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论