Performance impact of vararg in Java [duplicate] - java

This question already has answers here:
Performance of variable argument methods in Java
(6 answers)
Java's varargs performance
(6 answers)
Closed 5 years ago.
I have few overloaded method, which I can replace with vararg, but these are getting called numerous times.
I just wanted to know its impact. I assume jvm creates an array from the parameters at runtime, so theoretically there must be some impact, not sure practically will it impact or not!

The one and only answer that makes sense here: go and measure yourself. Yes, you are correct - varargs are syntactic sugar - and the compiler creates arrays under the hood. So, yes - there is a certain performance impact.
But if that penalty really matters to you depends solely on your requirements and your context.
I think (opinion) here: when this really impacts the perceived performance of your application - then you probably have other problems already.

Related

Why is `Set.of()` implemented differently from `Collections.emptySet()`? [duplicate]

This question already has an answer here:
Map.of() vs. Collections.emptyMap()
(1 answer)
Closed 1 year ago.
As far as I can see, the contracts of both are identical. Seems rather pointless to implement a whole new empty set for Set.of().
I would presume the standard library implementors are aware of Collections.emptySet(), so there must be a specific reason I am not seeing. Due to the very generic method names, searching in mailing lists is impossible, so I am not sure if this was discussed.
(BTW, it seems Set.of() just uses a SetN with an empty input array, so it will probably be less efficient than emptySet() as well.)
There is a single difference "code-wise", that I am aware of.
Collections.emptySet().contains(null); // false
Set.of().contains(null); // NullPointerException
So they are not inter-changeable.
Set.of() uses a nice clean helper from ImmutableCollections which was introduced with Java 9.
Collections on the other hand was says since 1.2, and was only "adapted" to generics and such things over time.
So:
the Collections implementation is historically grown, and you would probably not be doing it like that any more today
so, when introducing the functionality in a new context, you do it in a different way.
And more importantly: all the of methods within Set are just delegating to ImmutableCollections. And then it makes no sense that of() would be implemented in a completely different way than all the other of(x) methods.

Constants in Ruby and Java's final keyword [duplicate]

This question already has answers here:
Closest Ruby representation of a 'private static final' and 'public static final' class variable in Java?
(4 answers)
Closed 6 years ago.
I have the following variable
CONSTANT =5
I wanted to test how Constants work in Ruby and was surprised to find out the following:
CONSTANT = 6
..results in CONSTANT actually being overwritten with a warning. I come from a java background where constants are just that, constant, thus I am a little confused as how Ruby accomplishes things.
My question is if there is any way to mimic javas final keyword in Ruby, thus not allowing a user to change the value of a variable?
Like a lot of things in Ruby there is no "final", things are inherently dynamic and absolutely preventing people from doing things is never really going to happen. You can just make it difficult.
The one thing to note is in Ruby there's a difference between immutable and constant. A constant is a variable which will generate a warning when reassigned, that's all, and there's nothing to prevent you from modifying it. To prevent modifications you must "freeze" the object in question, though as with all things in Ruby, this is just a request that can be ignored by the object.
Typically you'll see code like this:
ADMIN_USER_TYPE = 'Admin'.freeze
Or this:
USER_TYPES = %w[
Admin
].freeze
The freeze call is to catch cases where the list might be mangled by some method by accident. It does not absolutely prevent this, it's more of a safety measure. Consider this code:
def user_labels(types)
types.map! { |t| [ t, t.downcase.to_sym ] }
end
Here a mistaken map! call would have the effect of rewriting the original array. In cases where you're calling it with a throw-away argument this is fine:
user_labels(%w[ Admin Test ])
When you're using the constant you'll permanently modify it, and that will cause it to get modified over and over each time it's called, creating a mess. The freeze flag trips a warning here and prevents that.
So the short answer is: No. The long answer is you have to be disciplined, the language will not prevent you from doing this if you're sufficiently determined. Pay attention to warnings and treat them seriously.

Is it more efficient to use getters or assign them to a variable? [duplicate]

This question already has answers here:
Java Method invocation vs using a variable
(14 answers)
Closed 9 years ago.
In the below scenario, all 3 getXxxxx() methods simple return a property of that class with no additional processing.
Is it more efficient for me to assign them to a temporary variable like I've done with workLimit, or should I just use the getter like I did with getCurrentWork()?
int x = 0;
int workLimit = entity.getCurrentWorkLimit();
JobSet jobSet;
JobSetQueue queue = workflowProcess.getQueue();
while (x < workLimit && (jobSet = queue.poll()) != null) {
getCurrentWork().addLast(jobSet);
}
The VM optimizes access to simple getters itself - but in fact you usually shouldn't care about it. Therefore, I would usually optimize code for readibility / maintainability instead of performance. Performance optimizations should be based on facts, not assumptions.
Assuming getCurrentWork() is just returning a variable itself, then the performance will be the same. I think that having the extra variable sometimes makes the code easier to read/scan especially when you have lots of them. In thise case, I'd probably just use the getter.
You are in essence buying one less stack operation, this is a micro-optimization and as such is almost completely useless, unless you are writing a real-time system.
At the end of the day, profile profile profile

Why isn't .length() a method for arrays in Java? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Java - Array’s length property
String.length() vs Array.length
I'm currently in my AP Computer Science class in high school and I came across this in my reading.
From what I understand, .length() is a method used for strings, but why isn't .length() a method when applied on arrays? I understand that they're different objects, but why didn't Java just make another method for finding the length of arrays?
I appreciate any response I get. Thanks!
Since arrays are fixed length defined at the time they are instantiated length is a public final field on the class. There is no need to make it a method since there is no calculation to be done at run time.
See this section of the Java Spec for details:
http://docs.oracle.com/javase/specs/jls/se7/html/jls-10.html#jls-10.7
Now, as for the design question of why they didn't provide an accessor method to obtain the value isn't specified. Perhaps this was done before any other convention was set and this is just a legacy thing. Only the language designers would know the "why" portion of their decision to do it this way.
Arrays are defined in the Java Language Specification #10.7. In particular:
The members of an array type are all of the following:
The public final field length, which contains the number of components of the array. length may be positive or zero.
[...]
I can't answer why this approach was chosen by the language designers.
Interestingly, it was already the case in the Oak specifications, which is the ancestor of Java.
I doubt that there's a good technical reason for this.
I suspect that this is one of those little inconsistencies that didn't get spotted early enough to get fixed without breaking a ton of code.

String.length() vs Array.length [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Why is String.length() a method?
Java - Array's length property
Was there a specific design/performance reason as to why String has a method for length but Array has a variable length?
There is no Array class in Java (other than in reflections). Arrays are "primitives" of a sort in Java and play by different rules from declared classes.
Certainly a length() method could have been defined on arrays, but the designers wanted to keep length as a property rather than a pseudo-method. (In part this may have made it easier for early Java implementations.) The reasons are somewhat buried in history.
(A better question is why Java couldn't decide whether to call the concept "length", "count", or "size" -- I always end up trying all three before I hit on the right one for an aggregating class.)

Categories

Resources