Which of these is more efficient in java? - java

I am wondering which of the following is the most efficient?
int x = 1, y = 2;
System.out.print(x+y)
or...
int x = 1, y = 2, z = 3;
System.out.print(z);
I'm guessing it's the first, but not sure - thanks.

The real answer is: talking about efficiency on such a level does not make any sense at all.
Keep in mind that the overall performance and efficiency of a Java program is determined by many many factors - for example when/how the JIT kicks in in order to turn byte code into machine code.
Worrying about such subtleties will not help you to create a meaningful, maintainable, "good OO" design. Heck; in your case, depending on context, it could even be that the compiler does constant folding and turns your whole thing into println(3) (as it is really straight forward to throw away those variables); so maybe in both cases, the compiler creates the exact same bytecode.
Dont get me wrong: it is fair to ask/learn/understand what compilers, JVMs and JITs do. But: dont assume that you can categorize things that easily into "A more efficient than B".

If you truly mean the case where you have supplied all the literal values like that, then the difference doesn't exist at all, at least not after your code is JIT-compiled. In either case you will have zero calculation done at runtime. The JIT compiler will work out the result and hardcode it into all its use sites. The optimization techniques involved are Constant Propagation and Constant Folding.

It would be second option as you do not need any memory for calculation. You're just print a number instead of adding them together and than printing.
This is simple example, so performance is not noticeable at this level..
Good practice is to assign the task appropriately to different functions.

Related

In Java, do using "shortcut" variables impact performance?

I have the following piece of code:
Player player = (Player)Main.getInstance().getPlayer();
player.setSpeedModifier(keyMap[GLFW_KEY_LEFT_SHIFT] ? 1.8f : 1);
if (keyMap[GLFW_KEY_W]) {
player.moveForward();
}
if (keyMap[GLFW_KEY_S]) {
player.moveBackward();
}
player.rotateTowards(getMousePositionInWorld());
I was wondering if the usage of a local variable (For the player) to make the code more readable has any impact on performance or whether it would be optimised during compilation to replace the uses of the variable seeing as it is just a straight copy of another variable. Whilst it is possible to keep the long version in place, I prefer the readability of having the shorter version. I understand that the performance impact if there was any would be miniscule, but was just interested if there would be any whatsoever.
Thanks, -Slendy.
For any modern compiler, this will most likely be optimized away and it will not have any performance implications. The few additional bytes used for storage are well worth the added readability.
consider these 2 pieces of code:
final Player player = (Player)Main.getInstance().getPlayer();
player.callmethod1();
player.callmethod2();
and:
((Player)Main.getInstance().getPlayer()).callmethod1();
((Player)Main.getInstance().getPlayer()).callmethod2();
There are reasons, why first variant is preferable:
First one is more readable, at least because of line length
Java compiler cannot assume that the same object will be returned by Main.getInstance().getPlayer() this is why second variant will actually call getPlayer twice, which could be performance penalty
Apart from the probably unneeded (Player) cast, I even find your version to be superior to having long worms of calls.
IMHO if you need one special object more than once or twice, it is worth to be saved in a local variable.
The local variable will need some bytes on the stack, but on the other hand, several calls are omitted, so your version clearly wins.
Your biggest performance hit will likely be the function lookup of the objects:
(Player)Main.getInstance().getPlayer();
Otherwise, you want to minimize these function calls if possible. In this case, a local var could save CPU, though if you have a global var, it might be a hair faster to use it.
It really depends on how many times this is done in a loop though. Quite likely you will see no difference either way in normal usage. :)

Overuse of Method-chaining in Java

I see a lot of this kind of code written by Java developers and Java instructors:
for ( int x = 0 ; x < myArray.length ; x++ )
accum += (mean() - myArray[x]) * (mean() - myArray[x] );
I am very critical of this because mean() is being invoked twice for every element in the array, when it only has to be invoked once:
double theMean = mean();
for ( int x = 0 ; x < myArray.length ; x++ )
accum += (theMean - myArray[x]) * (theMean - myArray[x]);
Is there something about optimization in Java that makes the first example acceptable? Should I stop riding developers about this?
*** More information. An array of samples is stored as an instance variable. mean() has to traverse the array and calculate the mean every time it is invoked.
You are right. Your way (second code sample) is more efficient. I don't think Java can optimize the first code sample to call mean() just once and re-use its return value, since mean() might have side effects, so the compiler can't decide to call it once if your code calls it twice.
Leave your developers alone, it's fine -- it's readable and it works, without introducing unnecessary names and variables.
Optimization should only ever be done under the guidance of a performance monitoring tool which can show you where you're actually slow. And, typically, performance is enhanced more effectively by considering the large scale architecture of an application, not line by line bytecode optimization, which is expensive and usually unhelpful.
Your version will likely run faster, though an optimizing compiler may be able to detect if the mean() method returns the same value every time (e.g. if the value is hard-coded or stored in a field) and eliminate the method call.
If you are recommending this change for efficiency reasons, you may be falling foul of premature optimization. You don't really know where the bottlenecks are in your system until you measure in the appropriate environment under appropriate loads. Even then, improved hardware is often more cost-effective solution than developer time.
If you are recommending it because it will eliminate duplication then I think you might be on stronger ground. If the mean() method took arguments too, it would be especially reasonable to pull that out of the loop and call the method once and only once.
Yes, some compilers will optimize this to just what you say.
Yes, you should stop riding developers about this.
I think your preferred way is better, but not mostly because of the optimization. It is more clear that the value is the same in both places if it does not involve a method call, particularly in cases where the method call is more complex than the one you have here.
For that matter, I think it's better to write
double theMean = mean();
for (int x=0; x < myArray.length; x++)
{ double curValue = myArray[x];
double toSquare = theMean - curValue;
accum += toSquare * toSquare;
}
Because it makes it easier to determine that you are squaring whatever is being accumulated, and just what it is that's being sqaured.
Normally the compiler will not optimize the method call since it cannot know whether the return value would be the same (this is especially true when mean processes an array as it has no way of checking whether the result can be cached). So yes the mean() method would be invoked twice.
In this case, if you know for sure that the array is kept the same regardless of the values of x and accum in the loop (more generally, regardless of any change in the program values), then the second code is more optimal.

Is there a performance implication of calling multiple objects in a row?

Call A:
double Value = Object.Object.Object.Object.DoubleValue;
Call B:
double Value : Object.DoubleValue;
If this were in a for loop and being called many times over and over would there be a performance loss for calling an object within an object or is it worth noting about?
Readbility is for programmers, optimizations are for compilers (and jit optimizations, to be honest).
Do whatever is the standard in your team and is more readable.
If after you do it you suspect some performance issue - use a profiler to check if it is indeed the case, and do adjustments accordingly.
is it not worth noting about?
Its could cost you tens of nano-seconds (is that important to you?) The JIT fairly good at optimising/caching reference look ups so placing them in local variable is unlikely to be mcuh faster. i.e. even if it matters there is unlikely to be something simple you can do about it.

For arrays of up to 10 elements: for loop copy or System.arrayCopy?

Assuming a 10 element or less Object[] in Java, what would be the fastest way of copying the array?
for(int i = 0;i < a.length;i++)
for(int i = 0,l = a.length;i < l;i++) // i.e. is caching array len in local var faster?
System.arrayCopy(a, 0, a2, 0, a.length);
The chances are that the difference between the three alternatives is relatively small.
The chances are that this is irrelevant to your application's overall performance.
The relative difference is likely to depend on the hardware platform and the implementation of Java that you use.
The relative difference will also vary depending on the declared and actual types of the arrays.
You are best off forgetting about this and just coding the way that seems most natural to you. If you find that your completed application is running too slowly, profile it and tune based on the profiling results. At that point it might be worthwhile to try out the three alternatives to see which is faster for your application's specific use-case. (Another approach might be to see if it is sensible to avoid the array copy in the first place.)
Caching the length isn't useful. You're accessing a field directly. And even is it was a method, the JIT would inline and optimize it.
If something had to be optimized, System.arraycopy would contain the optimization.
But the real answer is that it doesn't matter at all. You're not going to obtain a significant gain in performance by choosing the most appropriate way of copying an array of 10 elements or less. If you have a performance problem, then search where it comes from by measuring, and then optimize what must be optimized. For the rest, use what is the most readable and maintainable. What you're doing is premature optimization. And it's the root of all evil (says D. Knuth).
System.arraycopy() is the fastest way to copy array -- as it designed and optimized exactly for this job. There was rumors that for small arrays it hadcoded loop may be faster -- but it is not true for now. System.arraycopy is a JIT intrinsics, and JIT choose best implementation for each case.
Do get yourself a book on JVM internals (for example, "Oracle JRockit, The Definitive Guide") and realize that what the JVM executes, after warming up, loop unrolling, method inlining, register re-allocation, loop invariant extraction and so on will not even closely resemble what you write in Java source code.
Sorry :-) Otherwise, you will enjoy reading http://www.javaspecialists.eu.

Will the compiler optimize repeated math computations?

Will the Java Compiler optimize simple repeated math operations like:
if (prevX / width != curX / width) {
// Do something with prevX / width value
} else {
// Do something with curX / width value
}
I know I can just assign the results to a variables before the if statement, and return the variables, but it's kind of cumbersome. If the compiler automatically recognizes that the same calculations are being made and caches the results to temporary variables on its own, I'd rather stick to the above convention.
*Edit - I'm an idiot. I tried to simply/abstract my question too much. It's not at simple as: if (x > y)
The answer is yes. This is called Common Subexpression Elimination and is a standard (and powerful) compiler optimization used in Java, C/C++ and others...
This page confirms that the HotSpot JVM will do this optimization.
That said, whether or not the compiler/run-time will be able to do this optimization when you expect it to is another story. So I usually prefer to do these optimizations myself if it also enhances readability.
double xw = x / width;
double yw = y / width;
if (xw > yw) {
return xw;
} else {
return yw;
}
The compiler may perform such optimizations. Whether it actually does depends on the answers to following:
Is the compiler allowed to do this by the JLS?
In some cases it is not. For instance if prevX was a volatile instance variable, then it must be fetched from memory each time the source code says it is used. Another case is where the common subexpression involves a method call with an observable side-effect; i.e. where something else in program might be able to tell if the method is called once or twice.
Is the compiler capable of doing this?
A compiler needs to analyze the code to detect common subexpressions that could legally be optimized. There two issues here:
Is the compiler capable of performing the necessary reasoning? For instance, one could hypothesize a compiler that can determine that a specific method call will be side-effect free and that therefore can be optimized. However, building a compiler that is actually capable of doing this is ... and interesting problem.
Is the optimization worthwhile? There is a trade-off between the cost of performing an optimization and the benefits. It is not a straight forward trade-off. It needs to take into account the cost of looking to see if an optimization can be performed ... when it actually can't. In other words, the impact on compilation time. (Bear and mind that in Java the optimizations are mostly done at runtime by the JIT compiler ... so this impacts on application performance.)
In a simple example like yours, the optimization is legal (modulo volatile) and one should expect a half-decent JIT compiler to perform it.
The other question is whether you should try to help the compiler by evaluating the common expressions explicitly your code and assigning the results to temporaries.
IMO, the answer is generally no.
A good compiler will probably do as good as job as you at this. And if it doesn't, then the next generation may do.
The code probably doesn't warrant hand optimization. Unless you've profiled your code to determine where the bottlenecks are, your hand optimizations stand a good chance of being irrelevant to actual application performance ... and a waste of your time.
There is a chance that you will stuff it up; e.g. by forgetting that a method call has an important side-effect or that a variable is volatile for a good reason.
On the other hand, if the rewrite makes your code more readable, that's a good reason to do it.
In general, "yes" - the compiler will optimize the code if it can, and the HotSpot JVM can also improve repeatedly-executed code blocks.
In this case however, you would be better to refactor the code like this:
if (x > y)
return x / width;
return y / width;
which avoids one division operation if x > y.

Categories

Resources