Is a ternary expression faster than Boolean logic? [duplicate] - java

This question already has answers here:
Is the ternary operator faster than an "if" condition in Java [duplicate]
(9 answers)
Closed 9 years ago.
This doesn't look like a duplicate, as only one my solutions involves a branch.
Essentially, which of these two lines is more efficient? will be a java app, but it'd be nice to know a general answer well.
shouldRefresh = useCache ? refetchIfExpired : true;
shouldRefresh = !useCache || refetchIfExpired;

The JIT compiler will figure out the fastest operation and use that. Use whatever makes the most sense to read. Don't optimize prematurely.
For interest's sake: If this were being compiled without optimizations, then the boolean operator would be faster. It's a simple mathematical operation, which takes just one CPU cycle (plus another for the ! operator), whereas the ternary expression would require a branch, which interrupts the pipeline if branch prediction guesses wrong.

I would not care about performance here, but about readability. With this aspect, the ternary operator wins in your example. By the way, I expect roughly the same performance.
You can also look how readability helps to save time in maintenance of code. So what is more important? Almost unmeasurable micro-optimization or easier understanding? And when you think a comment shall fix this, so I consider this as an unnecessary writing effort which also costs time.

Related

Why was arg = args[n++] more efficient than 2 seperate statements in earlier compilers?

From the Book "Core Java for the Impatient", Chapter "increment and decrement operators"
String arg = args[n++];
sets arg to args[n], and then increments n. This made sense thirty
years ago when compilers didn’t do a good job optimizing code.
Nowadays, there is no performance drawback in using two separate
statements, and many programmers find the explicit form easier to
read.
I thought such usage of increment and decrement operators was only used in order to write less code, but according to this quote it wasn't so in the past.
What was the performance benefit of writing statements such as String arg = args[n++]?
Some processors, like the Motorola 68000, support addressing modes that specifically dereference a pointer, then increment it. For instance:
Older compilers might conceivably be able to use this addressing mode on an expression like *p++ or arr[i++], but might not be able to recognize it split across two statements.
Over years architectures and compilers became better. Given the improvements in architectures of CPUs and compilers I would say there is no single answer to it.
From the architecuture standpoint - many processors support STORE & POINTER AUTO-INCREMENT as a one CPU cycle. So in the past - the way you wrote the code would impact the result (one vs more operations). Most notably DSP architectures were good at paralleling things (e.g. TI DSPs like C54xx with post-increment and post-decrement instructions and instructions that you can execute in circular buffers - e.g. *"ADD *AR2+, AR2–, A ;after accessing the operands, AR2 ;is incremented by one." - from TMS320C54x DSP reference set). ARM cores also feature instructions that allows for similar parallelism (VLDR, VSTR instructions - see documentation )
From the compiler standpoint - Compiler looks at how variable is used in its scope (what could not be the the case before). It can see if the variable is reused later or not. It might be the case that in the code a variable is increased but then discarded. What is the point of doing that?Nowadays compiler has to track variable usage and it can make smart decisions based on that (if you look at Java 8 - the compiler must be able to spot "effectively final" variables that are not reassigned).
These operators were/are generally used for convenience by programmers rather than to achieve performance. Because effectively, the statement would get split into a two line statement during compilation!! Apparently, the overhead for performing Post/Pre-increment/decrement operators would be more as compared to an already split two liner statement!

How to compare two logical expressions from SQL where condition? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I want two compare two SQL where clauses to check if the conditions are similar.
In the below example the SQL queries have same logical conditions in the where clause. What operation shall tell me that both where clause conditions are logically same?
Is there a REGEX for this? Any other approach?
String Q3 = "select t1.ID as ID,t1.FIELD8 as I_RECHARGE_TYPE,t1.FIELD28 as I_RECHARGE_AMOUNT,t1.FIELD1 as I_ACTIVATION_DATE,t1.FIELD2 as I_MSISDN from INSTANT_CDR_0 as t1 where t1.FIELD2 = ? and ((((t1.FIELD8 IS NOT NULL AND t1.FIELD28 > 0) OR DATE_FORMAT(t1.FIELD1,'%Y-%m-%d') > '2016-05-21')) or ((DATE_FORMAT(t1.FIELD1,'%Y-%m-%d') < '2015-12-03' OR ( t1.FIELD28 > 0 AND t1.FIELD28 < 101))))";
String Q4 = "select t1.ID as ID,t1.FIELD1 as I_ACTIVATION_DATE,t1.FIELD8 as I_RECHARGE_TYPE,t1.FIELD28 as I_RECHARGE_AMOUNT,t1.FIELD2 as I_MSISDN from INSTANT_CDR_0 as t1 where t1.FIELD2 = ? and (((DATE_FORMAT(t1.FIELD1,'%Y-%m-%d') > '2016-05-21' OR ( t1.FIELD8 IS NOT NULL AND t1.FIELD28 > 0))) or (((t1.FIELD28 > 0 AND t1.FIELD28 < 101) OR DATE_FORMAT(t1.FIELD1,'%Y-%m-%d') < '2015-12-03')))";
How to compare ((a=2) and (b=3)) with ((b=3) and(a=2)) and figure out they're the same?
A simpler case would be if all the fields you had were booleans. So all the logical expressions would also be boolean expressions.
What you'd then have would be the problem of trying to find out if two boolean expressions are equivalent - that is, for every possible input they provide the same answer.
One approach to doing this might be this: Let A be the first expression and B the second expression and A and B the logical and of the two. For the two expressions to be equivalent A and B applied to all possible inputs must be true. Which means not (A and B) must be false for all inputs. Thus, the last problem becomes a Boolean satisfiability problem. This problem asks whether, for a boolean expression, there exists at least one assignment of inputs which makes it true. If there is, then you can say that the two expressions are not equivalent using our construction, otherwise you say they are equivalent.
The good news is that there's loads of tools for attacking the problem, called SAT-solvers, which are used in a ton of industrial applications (circuit design, for example).
The bad news is that the problem is NP-complete. So it's a really hard one. If the setup of the problem does not lend itself to the usual heuristics employed by SAT-solvers, you're gonna have to wait a while to get your results (perhaps till the heat death of the Universe?).
The worse news is that SAT solvers are focused on boolean problems, while you have SQL data types, which are more general problems. Developing the tooling for solving that is on you, unfortunately.
All this on top of, as others have mentioned, needing to parse the expression.
Depending on how exact you want the result to be, you can do this trick: run the two queries. If they provide the same result, say the expressions are equivalent. If not, say they aren't. What you have here is a situation where you can have false positives, but no false negatives. So, if you say two expressions aren't equivalent, then that's a fact, you can't deny that, because otherwise they'd have provided the same answer. But if you say they are equivalent, there's some chance they're actually not, and you got lucky with your data. If people add more data in the future in the tables, the two won't be equivalent. There's a bit of math here involved, and I won't sketch it in this answer, but, if one makes some assumptions about the input table/tables and one also has enough rows in the tables, the probability of a false positive, that is, of you saying two expressions are equivalent, when in fact they aren't, drops pretty low - exponentially so. So if you have something like 1000 rows to test these things on, you can be pretty sure that a match is good.
You could also do algebraic manipulations on the expressions, trying to bring one to the form of the other. There's a whole set of them one can apply, from boolean expressions (DeMorgan rules, associativity, Karnaugh Maps, etc.), which perhaps might help in finding an exact solution, especially if the where clauses are simple, but that would seem more fragile to me.
Hope this helps. Make sure to order the results of the queries, so you don't discard real matches.
Simple/simplified approach that may not be good enough (initially I didn't see your comment about checking logically). As others pointed out, without relaxations, this problem is NP-Complete...
Use something like JSQLParser to get a structured representation and then traverse the object model and try to compare between the conditions. I would try to make a function that compare two expression and check for equality. This function could be called recursively in case of expressions with deep nesting/parenthesizing.
Try to use regex to split the where clause into conditions and then compare. Here you'd have to be careful with OR/AND and parenthesis... ideally, you'll want to end up with some hierarchical structure that preserve meaning of parenthesizing.
I tend to believe that the first approach would be easier as you won't have to break your neck with breaking/grouping of the conditions based on parenthesis etc.

Java isEmpty or "".equals for performance [duplicate]

This question already has answers here:
Should I use string.isEmpty() or "".equals(string)?
(6 answers)
Closed 7 years ago.
I'm writing a lot of components in Adobe CQ so have to deal a lot with user set properties. And i'm getting a little tired of all the null checks before I can do an isEmpty check.
I'd like to do something like.
"".equals(string);
This would be a lot more readable, but how would it compare performance wise. And yes i would expect to create the "" as a constant if there where multiple checks.
Thanks
D
Personally I use Apache's StringUtils, eg:
if (StringUtils.isEmpty(someString)) {
...
or
if (StringUtils.isNotEmpty(someString)) {
...
Also I really wouldn't worry about the performance of this unless you have benchmarked an identified it as an issue
It is preferred to use the isEmpty() method(Simpler and faster source code ).
Another efficient way to check empty string in java is to use:
string.length() == 0;
You should not care about performance here. Both version have similar speed. Even if they compile differently, JITted code will unlikely to differ more than several CPU cycles (especially given the fact that String.equals is JVM intrinsic). Not the thing you should worry about when programming on Java.

Why should I learn "switch case" when "if else" already exists [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Advantage of switch over if-else statement
Why Switch/Case and not If/Else If?
I am currently learning "switch case" in school and am wondering what's the point of learning it when "if else" already exists. "if else" is basically another way of doing "switch case".
Please correct me if i am wrong.
It kinda nostalgic to heard it. Both of them actually 'looked' the same. But is a little bit different when the codes executed.
Firstly, 'switch-case' is about comparing value-only. But 'if-else' could process a boolean expression (which would support much more complex clauses)
If you use general 'if-else' when you have found what you are actually searching for, the process will still run until it has finished processing the last if (but actually it could use jump-technique to have similar mechanism like 'switch-case'.)
It won't happen if you use 'switch-case' because once the value you're searching for has been found, it will break and won't continue to the next case. Also, 'switch-case' is faster-to-process than if else because it only compares defined values (not expression). And 'switch-case' also has a good formatting structure (it's simple, compact, readable and clean).
The more tools you have the better. Flat out the best statement of why you should know both... however a more detailed example -
A switch statement works on a single type of variable of the construct:
variable == value
So for example in C if you were trying to compare something to a few different strings in order to make a decision, you can't do that with a switch. In this case you need to know about the if/else constructs.
However if you have a large number of sequential checks:
var == 1 or
var == 2 or
var == 3 etc
The compiler may take your switch statement and convert it to a jump table, which would end up being faster than a large number of comparisons that an if/else list would be.
You should learn the switch construct because it is a useful tool provided by the C language.
It is not the same as if-else blocks.
In the comments section of your question, there are links to existing StackOverflow answers explaining what the differences are.
Each construct has its strengths and weaknesses, and over time you will learn when it is appropriate to choose one over the other.
You should learn both. While it is technically possible to implement any if / else sequence with a switch and vice versa, it would be extremely bad practice to do this ... in most cases.
So you need to learn the two constructs, understand their strengths and weaknesses, and learn to use your judgement as to when it is appropriate to use each one.
And the mere fact that C and C++ and Java (and C# and Pascal and many other languages) all support switch statements should tell you something about its usefulness ...
Difference between switch-case and if-else constructs:
Switch-case switches on values only, it does not evaluates boolean expressions.
Switch-case offers execution of next cases below it automatically if you don't use break after your case block. This feature is sometimes useful for writing complex code, like "Telephone Dial Plan"
Switch-case are more elegant compared to if-else when the number of comparisons are huge, like in displaying "Menu", etc.

String.equals() argument ordering

I recently received a downvote for using the following in a recent answer:
String word = ...;
if ("s".equals(word) || "y".equals(word)
The downvote was given due to using a "yoda condition". I asked for further explanation but none was provided. I prefer this style to avoid a possible NullPointerException.
Is this a poor coding style? If so, why?
Bill Pugh asked this question at Devoxx 2011. The vast majority of people went for the form "xyz".equals(str). I am with Bill, now preferring str.equals("xyz").
It's fundamental to the Java tradition that we find errors as early as reasonably possible. NPEs are exceptionally common. We want to route these nulls out as soon as possible.
If you're expecting the reference to maybe null, then I don't particularly object to the backwards notation. It's nice to be explicit and easier to understand that there may be a null with a separate null check, but the reverse order should be well understood and sufficiently differentiate the code from the normal case where null is forbidden.
Working in security, some of the bugs null-tolerance accommodates are vulnerabilities.
Yoda conditions (i.e. putting a constant before a variable in a comparison) can be considered bad practice as it makes the line of code less comprehensible. In this specific case however I would state that using a Yoda condition makes the code more comprehensible as you don't have to put a extra null check in front of it.
Visit the following link to understand what is meant by Yoda Conditions|Notation
Its not a "poor coding style" its diferent way of coding.
Yoda can be usefull to track typos in some languages, i believe the -1 was not deserved to be honest but that is my personal opinion.
But Yoda can be bad as explained in this lengthy but very interesting article.
End of the day, there are supporters in favor and against this kinda of notation.
Well, it depends. If in your program "word" should never be null, word.equals("s") may actually be better. If for some obscure reason "word" will become null, you will get NullPointerException.
Think about it. If you get exception, you know something went wrong, and you can faster find mistake and fix it. If program will continue to work silently, and produce wrong results, it will be much harder to detect the problem. Actually, you may not notice there is the problem at all.
It all depends.
There are several reasons not to do it like that, however in the end it depends on you (or the team working on your product) if you think this is bad coding style. Arguments against it are:
Strings are rarely null (and you shouldn't make APIs where they are because people don't expect it)
It feels weird to put the value you are comparing to first
Code style uniformity is important, because this way is the exception, you should only do it, if everyone in your team does it.
As said I don't think these arguments are very strong, nor is the reason to do it like you. So it is mostly important to just agree on one way as your coding style and stick to that.
TL;DR; This definitely is poor coding style NOT :D
well, the yoda conditions are useful in languages where non-boolean can evaluate to a boolean value, e.g.
int test = 0;
if ( test ){ /* do something */
but this is not allowed in Java so you don't run into problems such as forgetting '=', e.g.
if ( test = 2 ){ /* do something */
instead of test == 2
the compiler will not let you do this. So the yoda condition may seem unnatural to someone who has not had to care about this (because he/she didn't use any other language but Java).
This definitely is NOT poor coding style it is just not very common to see Java code using it
yoda condition is where oup put the literal in front of the variable.
word.equals("s") is read as "word equals s"
"s".equals(word) a human reads as "s equals word"
Our brains read the first example much better and the code is clearer.
the only reason imho to use yoda conditions is to prevent assignment
as in "if (42 = i)" instead of "if(42 == i)"
You can write
if (word != null && (word.equals("s") || word.equals("y")))
instead of
if ("s".equals(word) || "y".equals(word))
In this case, first one will never cause any NullpointerException, but in my point of view in this case the 2nd one is better, though it is in Yoda Condition
There is a special case pf Yoda conditional I've not seen defended, or attacked, in any of the answers, so I'll add it for reference. This is the style of:
if(0 < x && x <= max) {
A Yoda conditional because the constant (0) is before the variable (x). The argument against Yoda conditionals is that is hinders readability. Contrast that example with the functionally equivalent
if(x <= max && x > 0) {
Do you really think that, non-Yoda variant, is more readable? I don't.
For readability when using ordering relational operators (<, <=, >, >=), I prefer the style of these heuristics:
Use consistent ordering relations: > is consistent with >=, but not with < or <=; < is consistent with <=.
Prefer < and <= to > and >=, as the default is ascending order.
Place conditions that impose a lower bound on the variable before conditions that impose an upper bound, if using < and <=. Do the opposite if using > and >=.
This very often produces a Yoda conditional for the lower bound.
One might argue that you should (unit-)test your code enough to be confident that nulls don't go where they're not supposed to. This should obviate the need for yoda conditions.

Categories

Resources