Java nested if conditions or all condition in the same if - java

I have a loop iteration that contains many conditions in this form
if (a[k]<=x){
if(al[k+1]==y){
if(a[k+2]>=x){
}
}
}
Is better use Use the conditions in and in a single if in terms of performance??
if ((a[k]<=x) && (al[k+1]==y) && (a[k+2]>=x)){
}

As others have noted, aim for readability and don't prematurely optimize code. Measure performance and if you identify this snippet of code to be a bottleneck, then start to think more seriously about the issue.
Also as stated in comments, the performance will likely be identical in this situation. You might find different performance characteristics if you re-ordered the predicates. Something like:
if(B && A && C)
if calculating A is inexpensive and returns false 90% of the time, and calculating B is very expensive, you could instead write:
if(A && B && C)
but again, don't shoot from the hip! Aim first for readable code, and if your measurements identify a performance bottleneck, then consider the above.

Actually, the compiler is enough "smart" to compile the two codes to the same bytecode java but, if you want my opinion, the first is better (because reading a lot of if if if is annoying).

If you have many complex conditions in your loop like you say, consider moving them into small methods for improved readability.
// inside loop
if (isValid(x, y, k)) {
}
// use a less generic method name in your code
private boolean isValid(int x, int y, int k) {
return a[k]<=x && al[k+1]==y && a[k+2]>=x;
}
In case you are now worried that this will cause bad performance, there is a good chance that the JVM will inline these methods.

Related

Is there a difference calling a function with a simple return over just doing the check?

Is there any difference between doing
if (numberOfEntries >= array.length) {do stuff}; // Check if array is full directly
over doing something like
private boolean isArrayFull(){
return numberOfEntries >= array.length;
}
if (isArrayFull()) {do stuff}; // Call a check function
Over large arrays, many iterations and any other environment of execution, is there any difference to these methods other than readability and code duplication, if I need to check if the array is full anywhere else?
Forget about performance. That is negligible.
But if you are doing it many times, util method isArrayFull() makes sense. Because if you are adding more conditions to your check, changing in the function reflects everywhere.
As said above, first make your design good and then determine performance issues, using some tools. Java has JIT optimisations for inlining, so there is no difference.
The JIT aggressively inlines methods, removing the overhead of method calls
from https://techblug.wordpress.com/2013/08/19/java-jit-compiler-inlining/
Note: The below explanation is not any language specific. It is generic.
The difference comes when you analyze the options at machine level, A function is actually some JMP operations and allot of PUSH/POP operations on the CPU. An IF is usually a single COMP operation which is much cheaper than any what happens during function call.
If your 'IF's usually return false/true then I won't worry about it as the CPU optimizes IFs in a very good way by predicting the result as long as the IFs are "predictable" (usually returns true or false or has some pattern of true/false)
I would go with the IFs in cases where even negligible improvement in performance is a big deal.
In cases like web applications reducing the code redundancy to make the code manageable and readable is way more important than the optimization to save a few instructions at machine level.

Should I use != or == first when implementing an if else for comparison

This has been bugging me for a while and I'm not sure if there is a correct answer:
Take these two statements
if(foo == bar)
do this;
else if(foo != bar)
do that;
or
if(foo != bar)
do that;
else if(foo == bar)
do this;
which one of these is correct (forgetting optimization for now)
My mind tells me that the answer depends on what result is expected for example if this was running in a loop and I predicted that foo will be equal to bar more times than it is not then the first one would be correct.
Is there any efficiency implications between the notations?
But is there any efficiency implications between the notations? No. None at all. Prefer the one that is most readable. If it reads better saying "if not a" in a sentence, use !. Otherwise, don't.
If you dont want to go for If...else condition , you can use ternary operator .
like
result = testStatement ? value1 : value2;
But for nested conditions , ternary operator looks very complex.
It really does make much of a difference, optimisation wise. It comes down to your style and preferences. Both of your examples have the same impact.
Why not just do this
if(foo == bar)
do this;
else
do that;
Seems clearer that way, and if you are returning any statements inside the conditional blocks, it makes the program more readable
If I understand correctly, you are asking about the difference between the following two snippets.
if (predicate1()) {
doThis();
} else if (predicate2()) {
doThat();
}
if (predicate2()) {
doThat();
} else if (predicate1()) {
doThis();
}
If predicate1 and predicate2 may both be true at the same time, there is a difference in the outcome, I am sure you are aware of that. So I will assume that at most one of them can be true. I am also assuming that we can safely ignore any side effects from evaluating the conditions.
Is there a readability difference? Not as the code stands. However, in a concrete situation it could well be that the average reader will find it more natural to evaluate one predicate first. If so, go by that.
You ask about efficiency. First answer is, you shouldn’t. But anyway, there are two guidelines, and I think you have touched on both already:
Evaluate the condition that is true most often first
Evaluate the condition that is cheapest to evaluate first
If we had numbers, we could make a fine piece of math calculating the average cost of each snippet and choose the best.
As to whether == or != is cheaper, with my attitude I obviously don’t know the answer. I would expect it to vary with the types you compare, with whether you are running byte code or native code, with your type of CPU and other factors. You may go measure, and there may be folks around that know a rule thumb or two. In any case, the difference has to be very minute.

Is in If condition the check obj == null more performance effective then obj!=null

According to one of my senior coding style 2 is better in performance than coding style 1,is it true ?
coding style 1
If (obj!=null)
{
Logic A
}
else
{
Logic B
}
coding style 2
If (obj==null)
{
Logic B
}
else
{
Logic A
}
In examples like this, it is developer performance you should worry about. What is the cleanest and simplest code and this will often be a pattern the JIT optimiser will do a good job, if not it's best job with.
In this example, even if you could measure a difference I would suspect
your test is broken.
the difference would be different on different machines or JVMs.
such a difference will disappear in future versions of Java.
BTW: Looking at the byte code is a very poor measure of performance, but I can say that the byte code generates and I suspect the native code generated will be the same length.
Whether or not it is faster to test for null or non-null can only be observed at the machine code level, which you have almost no control over. Your Java file will be compiled to bytecode and then, at runtime, this bytecode will be compiled again to machine code by the Just-in-Time compiler (JIT). The JIT performs all kids of advanced optimizations, one of which could be the reordering of branches with inversion of branching conditions.
Note that the CPU cycles spent on testing the value of the variable will be dwarfed by the penalty in branch misprediction, so correct branch prediction is the JIT compiler's foremest concern. You have absolutely zero control of these subtleties on the level of Java source code.
Therefore the unanimous advice is to take care to write code which reads most naturally and don't spend a second thinking on the peformance differential of branch ordering.
Performance should not make a difference as Peter Lawrey pointed out.
I guess your friend didn't talk about performance but about coding style.
When using if elseconstructs people often find it preferable to first handle the non-negated case in the if block before handling the negated case in the else block.
So one better writes
if (a == b) {
logicA();
}
else {
logicB();
}
instead of writing
if (a != b) {
logicB();
}
else {
logicA();
}
as it usually leads to better readability.
Your senior should provide "measurable" test cases to prove to you which logic is better.
You shouldn't worry about optimization logic as the compiler does all the optimization for you. Rather, focus on readability of code (and flow logic?). Example, Java 7 introduced <T> T Objects.requireNotNull(T obj) method, which internally does:
if (obj == null) {
throw new NullPointerException();
}
return x;
Which is better, especially when creating API's as you have a business logic that "asserts"/guarantees not null.

Recursion or Looping [duplicate]

This question already has answers here:
Recursion or iteration?
(14 answers)
Closed 2 years ago.
I have this method that calculates some statistics:
public void calculateAverage(int hour){
if (hour != 20) {
int data =0;
int times = 0;
for (CallQueue cq : queues) {
data += cq.getCallsByTime().get(hour);
times++;
}
averageData.add((double)data/times);
calculateAverage(hour + 1);
}
}
Now I am very proud that I have created a recursive method but I know that this could have been solved with a loop.
My question is: is it better to solve these kind of problems recursive or with a loop?
Recursion in general
In general, a recursion would be more expensive, because the stack has to be modified with copies of variables for each time the function recurses.
A set of addresses & states need to be saved, so that the recursive procedure can return to the right state after that particular run.
Iteration would be better if possible. Recursion, when iteration just won't cut it, or will result in a lot more complicated code.
Code Maintenance
From a maintenance perspective, debugging iterative code is a lot easier than recursive procedures as it is relatively easier to understand what the state is at any particular iteration, as compared to thinking about a particular recursion.
Your code
The procedure calls itself, but each run has nothing to do with the results of the previous run. Each run being independent, is usually the biggest give-away, that recursion there might not be necessary.
In my opinion, calculateAverage(hour + 1); should be moved outside the function, as it would also be clearer to someone reading your code. that each call is independent.
In Java, C, and Python, recursion is fairly expensive compared to iteration (in general) because it requires the allocation of a new stack frame. In some C compilers, one can use a compiler flag to eliminate this overhead, which transforms certain types of recursion (actually, certain types of tail calls) into jumps instead of function calls. (source)
For this particular problem there isn't too much of a runtime difference. I personally would rather use iteration, I think it would be more simple and easier to understand, but to each his own I suppose.
now some recursive functions(like recursive Fibonacci numbers for example) should be done by iteration instead, simply because they can have exponential growth.
generally, I don't use recursion unless It would make my problem actually easier to understand.
You should investigate the perimeter circumstances. For big recursions stack might get overflow, thats +1 for loops.
I'm not sure which one runs faster but that is relatively easy to measure, taking JIT and other stuff into considerations.
Code maintenance aspect: it is much easier for the most of us to understand and fix loops than recursion. Developers time is usually more important than minor performance differences.
It depends on the context. For example if I have a tree of Composite objects (in SWT) and you wish to traverse them the easiest way is to use recursion like this:
private boolean checkControlParent(Composite comp) {
boolean ret = false;
if (comp != null) {
if (this.equals(comp)) {
ret = true;
} else {
ret = checkControlParent(comp.getParent());
}
}
return ret;
}
otherwise if performance is important be advised that recursive calls are slower in most cases than simple loops because of the function/method call overhead.
So the main thing is that if you need to iterate through objects where recursion is a natural solution and you don't risk a StackOverflowError go ahead and use recursion. Otherwise you'll probably better off with a loop.
One more thing: recursive methods are sometimes tend to be harder to read, understand and debug.

Should I avoid using Java Label Statements?

Today I had a coworker suggest I refactor my code to use a label statement to control flow through 2 nested for loops I had created. I've never used them before because personally I think they decrease the readability of a program. I am willing to change my mind about using them if the argument is solid enough however. What are people's opinions on label statements?
Many algorithms are expressed more easily if you can jump across two loops (or a loop containing a switch statement). Don't feel bad about it. On the other hand, it may indicate an overly complex solution. So stand back and look at the problem.
Some people prefer a "single entry, single exit" approach to all loops. That is to say avoiding break (and continue) and early return for loops altogether. This may result in some duplicate code.
What I would strongly avoid doing is introducing auxilary variables. Hiding control-flow within state adds to confusion.
Splitting labeled loops into two methods may well be difficult. Exceptions are probably too heavyweight. Try a single entry, single exit approach.
Labels are like goto's: Use them sparingly, and only when they make your code faster and more importantly, more understandable,
e.g., If you are in big loops six levels deep and you encounter a condition that makes the rest of the loop pointless to complete, there's no sense in having 6 extra trap doors in your condition statements to exit out the loop early.
Labels (and goto's) aren't evil, it's just that sometimes people use them in bad ways. Most of the time we are actually trying to write our code so it is understandable for you and the next programmer who comes along. Making it uber-fast is a secondary concern (be wary of premature optimization).
When Labels (and goto's) are misused they make the code less readable, which causes grief for you and the next developer. The compiler doesn't care.
There are few occasions when you need labels and they can be confusing because they are rarely used. However if you need to use one then use one.
BTW: this compiles and runs.
class MyFirstJavaProg {
public static void main(String args[]) {
http://www.javacoffeebreak.com/java101/java101.html
System.out.println("Hello World!");
}
}
I'm curious to hear what your alternative to labels is. I think this is pretty much going to boil down to the argument of "return as early as possible" vs. "use a variable to hold the return value, and only return at the end."
Labels are pretty standard when you have nested loops. The only way they really decrease readability is when another developer has never seen them before and doesn't understand what they mean.
I have use a Java labeled loop for an implementation of a Sieve method to find prime numbers (done for one of the project Euler math problems) which made it 10x faster compared to nested loops. Eg if(certain condition) go back to outer loop.
private static void testByFactoring() {
primes: for (int ctr = 0; ctr < m_toFactor.length; ctr++) {
int toTest = m_toFactor[ctr];
for (int ctr2 = 0; ctr2 < m_divisors.length; ctr2++) {
// max (int) Math.sqrt(m_numberToTest) + 1 iterations
if (toTest != m_divisors[ctr2]
&& toTest % m_divisors[ctr2] == 0) {
continue primes;
}
} // end of the divisor loop
} // end of primes loop
} // method
I asked a C++ programmer how bad labeled loops are, he said he would use them sparingly, but they can occasionally come in handy. For example, if you have 3 nested loops and for certain conditions you want to go back to the outermost loop.
So they have their uses, it depends on the problem you were trying to solve.
I've never seen labels used "in the wild" in Java code. If you really want to break across nested loops, see if you can refactor your method so that an early return statement does what you want.
Technically, I guess there's not much difference between an early return and a label. Practically, though, almost every Java developer has seen an early return and knows what it does. I'd guess many developers would at least be surprised by a label, and probably be confused.
I was taught the single entry / single exit orthodoxy in school, but I've since come to appreciate early return statements and breaking out of loops as a way to simplify code and make it clearer.
I'd argue in favour of them in some locations, I found them particularly useful in this example:
nextItem: for(CartItem item : user.getCart()) {
nextCondition : for(PurchaseCondition cond : item.getConditions()) {
if(!cond.check())
continue nextItem;
else
continue nextCondition;
}
purchasedItems.add(item);
}
I think with the new for-each loop, the label can be really clear.
For example:
sentence: for(Sentence sentence: paragraph) {
for(String word: sentence) {
// do something
if(isDone()) {
continue sentence;
}
}
}
I think that looks really clear by having your label the same as your variable in the new for-each. In fact, maybe Java should be evil and add implicit labels for-each variables heh
I never use labels in my code. I prefer to create a guard and initialize it to null or other unusual value. This guard is often a result object. I haven't seen any of my coworkers using labels, nor found any in our repository. It really depends on your style of coding. In my opinion using labels would decrease the readability as it's not a common construct and usually it's not used in Java.
Yes, you should avoid using label unless there's a specific reason to use them (the example of it simplifying implementation of an algorithm is pertinent). In such a case I would advise adding sufficient comments or other documentation to explain the reasoning behind it so that someone doesn't come along later and mangle it out of some notion of "improving the code" or "getting rid of code smell" or some other potentially BS excuse.
I would equate this sort of question with deciding when one should or shouldn't use the ternary if. The chief rationale being that it can impede readability and unless the programmer is very careful to name things in a reasonable way then use of conventions such as labels might make things a lot worse. Suppose the example using 'nextCondition' and 'nextItem' had used 'loop1' and 'loop2' for his label names.
Personally labels are one of those features that don't make a lot of sense to me, outside of Assembly or BASIC and other similarly limited languages. Java has plenty of more conventional/regular loop and control constructs.
I found labels to be sometimes useful in tests, to separate the usual setup, excercise and verify phases and group related statements. For example, using the BDD terminology:
#Test
public void should_Clear_Cached_Element() throws Exception {
given: {
elementStream = defaultStream();
elementStream.readElement();
Assume.assumeNotNull(elementStream.lastRead());
}
when:
elementStream.clearLast();
then:
assertThat(elementStream.lastRead()).isEmpty();
}
Your formatting choices may vary but the core idea is that labels, in this case, provide a noticeable distinction between the logical sections comprising your test, better than comments can. I think the Spock library just builds on this very feature to declare its test phases.
Personally whenever I need to use nested loops with the innermost one having to break out of all the parent loops, I just write everything in a method with a return statement when my condition is met, it's far more readable and logical.
Example Using method:
private static boolean exists(int[][] array, int searchFor) {
for (int[] nums : array) {
for (int num : nums) {
if (num == searchFor) {
return true;
}
}
}
return false;
}
Example Using label (less readable imo):
boolean exists = false;
existenceLoop:
for (int[] nums : array) {
for (int num : nums) {
if (num == searchFor) {
exists = true;
break existenceLoop;
}
}
}
return exists;

Categories

Resources