[英]Should we pass argument to a method as a variable or as a new object directly in java
Consider the following two calls to the same method in java:- 考虑以下两个对java中相同方法的调用:
1) doSomething(new Object[]{"something"}) ;
1) doSomething(new Object[]{"something"}) ;
2) 2)
Object[] obj = {"something"} ;
doSomething(obj);
Which one is more efficient in terms of memory and time efficiency ? 就内存和时间效率而言,哪一个更有效? I would say the 1) is better in both memory and time efficiency. 我会说1)在记忆和时间效率上都更好。 Reason being in the second option requires us to create another variable (extra memory) and then assigns that value to the variable (extra time). 原因是第二种选择,要求我们创建另一个变量(额外的内存),然后将该值分配给变量(额外的时间)。 Any comments ? 任何意见 ?
Just to clarify the object will be create only once, i am talking about the extra variable being used to hold the address of the newly created object. 只是为了澄清该对象将仅创建一次,我说的是用于容纳新创建对象地址的额外变量。
Both are the same in terms of time and memory. 两者在时间和记忆方面都相同。 The extra assignment can be optimized away by the compiler. 编译器可以优化额外的分配。
A difference is that the second version gives you an opportunity to give a useful name to your variable, which can make the code more clear. 不同之处在于第二个版本使您有机会为变量指定一个有用的名称,从而使代码更清晰。
The second call allows you to reuse the object in the calling method, but the first one does not. 第二个调用使您可以在调用方法中重用该对象,但第一个则不能。
It has no incidence on memory, as the passed object is created anyway. 它不会在内存中产生任何影响,因为无论如何都会创建传递的对象。
You should always consider what is simpler and clearer first. 您应该始终首先考虑更简单和更清晰的内容。 You should only consider performance when you know you have a problem because you measured it in a profiler or micro-benchmark. 仅当您知道存在问题时才应考虑性能,因为您是通过性能分析器或微基准测试对其进行测量的。
The best option is likely to be to use varargs 最好的选择可能是使用varargs
doSomething("something");
void doSomething(String... args) { }
Note: not only is the this simplest, but it is also potentially the fastest as the JIT can eliminate the String[]
created. 注意:这不仅是最简单的,而且可能是最快的,因为JIT可以消除创建的String[]
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.