Reputation: 2031
I have a question about creating new object in java.
Lets say i have methos called: foo(String[] a)
I want to pass to foo
a new String[]
thats is only for one use what is better for
performance 1 or 2
1.
String[] a = new String[]{"a"};
foo(a);
2.
foo(new String[]{"a"});
Thanks for helping
Upvotes: 1
Views: 361
Reputation: 129507
You can check the bytecode:
1.
public static void main(java.lang.String[]);
Code:
0: iconst_0
1: anewarray #2 // class java/lang/String
4: astore_1
5: aload_1
6: invokestatic #3 // Method foo:([Ljava/lang/String;)V
9: return
2.
public static void main(java.lang.String[]);
Code:
0: iconst_0
1: anewarray #2 // class java/lang/String
4: invokestatic #3 // Method foo:([Ljava/lang/String;)V
7: return
The only difference is that in (2), no references are stored (astore_1
) and none need to be loaded (aload_1
). This will almost certainly not cause a performance difference (and you shouldn't worry about such minuscule optimizations anyway), but you might as well use option (2) if you're not going to reference a
again in the program (as you mentioned in your comment) and there is no readability infringement.
I think the readability component is quite important: I would much rather create a variable to store the array (even if I'll never reference this variable more than once) than have one super-long, unreadable line. Of course, in your example, there is no issue with readability, but it's something to consider when more complicated situations arise.
Upvotes: 9
Reputation: 1841
I don't think it's possible to answer the question definitively in a general way. Even arshajii's response showing the IL is bounded.
In your code the JIT compiler will optimize this away anyway.
The level of optimization will depend heavily on things like version, platform, implementation, and a million other variables.
... now, if you had a read fence between the two, so the jitter couldn't optimize them away, then you would have a different story.
Upvotes: 2
Reputation: 236004
Having temporary local variables can help performance if you use them to store frequently used, costly-to-calculate values. For one-shot values, they still can be a big help for naming a value and making clear its intent - and the performance cost of this will be absolutely negligible.
Having or not having a variable for storing a one-shot-value is irrelevant in terms of performance, concentrate your efforts in the parts of the code highlighted as bottlenecks by a profiler, and don't waste your time in such irrelevant micro-optimizations. And it's more important to write code that's easy to understand, remember ... "premature optimization is the root of all evil."
Upvotes: 3