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

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.

Related

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

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.

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.

Java Double Comparison [duplicate]

This question already has answers here:
comparing float/double values using == operator
(9 answers)
Closed 5 years ago.
Are there any java libraries for doing double comparison?
e.g.
public static boolean greaterThanOrEqual(double a, double b, double epsilon){
return a - b > -epsilon;
}
Every project I start I end up re-implementing this and copy-pasting code and test.
NB a good example of why its better to use 3rd party JARs is that IBM recommend the following:
"If you don't know the scale of the underlying measurements, using the
test "abs(a/b - 1) < epsilon" is likely to be more robust than simply
comparing the difference"
I doubt many people would have thought of this and illustrates that even simple code can be sub-optimal.
Guava has DoubleMath.fuzzyCompare().
In the standard Java library there are no methods to handle your problem actually I suggest you to follow Joachim's link and use that library which is quite good for your needs, even though my suggestion would be to create an utils library in which you could add frequently used methods as the one you've stated in your question, as for different implementations of your problem you should consider looking into this :
Java double comparison epsilon
Feel free to ask out any other ambiguities
You should abstain from any library that uses the naive "maximum absolute difference" approach (like Guava). As detailed in the Bruce Dawson's excellent article Comparing Floating Point Numbers, 2012 edition, it is highly error-prone as it only works for a very limited range of values. A much more robust approach is to use relative differences or ULPs for approximate comparisons.
The only library I know of that does implement a correct approximate comparison algorithm is apache.common.math.

diff implementation in Java [duplicate]

This question already has answers here:
How to perform string Diffs in Java?
(9 answers)
Closed 5 years ago.
I'm looking for a diff implementation in Java. I've seen that Python has its own SequenceMatcher (with difflib), which is exactly what I need... in Java.
Is there any portage? Or is there any other class/library that performs the same in Java?
If not, where can I find the source code of that difflib (if free as in speech) to make my own implementation of SequenceMatcher in Java ?
Unfortunately, Apache Commons Lang doesn't help me much.
Thanks!
This library seems to be what you're after: google-diff-match-patch.
It has the following main features:
Diff: Compare two blocks of plain text and efficiently return a list of differences.
Match: Given a search string, find its best fuzzy match in a block of plain text. Weighted for both accuracy and location.
Patch: Apply a list of patches onto plain text. Use best-effort to apply patch even when the underlying text doesn't match.
In case you want an alternative, you could also try this: java-diff-utils
Hi You can run a MR job which can use https://code.google.com/p/google-diff-match-patch/ to do the required job. I dont feel there are any tools out of the box to do your job.

Closures in Java 7 [duplicate]

This question already has answers here:
Closure in Java 7 [closed]
(7 answers)
Closed 6 years ago.
I have heard that closures could be introduced in the next Java standard that is scheduled to be released somewhere around next summer.
What would this syntax look like?
I read somewhere that introducing closures in java is a bigger change than generic was in java 5. Is this true? pros and cons?
(By now we definitely know that closures not will be included in the next Java release)
OR
edit: http://puredanger.com/tech/2009/11/18/closures-after-all/ :D
edit2: Re-thinking JDK7: http://blogs.oracle.com/mr/entry/rethinking_jdk7
edit3: There’s not a moment to lose!: http://blogs.oracle.com/mr/entry/quartet
Have a look at http://www.javac.info/ .
It seems like this is how it would look:
boolean even = { int x => x % 2 == 0 }.invoke(15);
where the { int x => x % 2 == 0 } bit is the closure.
It really depends on what gets introduced, and indeed whether it will be introduced at all. There are a number of closure proposals of varying sizes.
See Alex Miller's Java 7 page for the proposals and various blog posts.
Personally I'd love to see closures - they're beautiful and incredibly helpful - but I fear that some of the proposals are pretty hairy.
In November 2009 there was a surprising u-turn on this issue, and closures will now be added to Java 7.
Update
Closures (AKA lambdas expressions) in Java 7 didn't happen. They were finally added in the first release of Java 8 in 2014.
Unofortunately you will not find closure in Java 7. If you are looking for a lighter solution to have closure in java just now check out the lambdaj project:
http://code.google.com/p/lambdaj/
This is the java 7 features http://tech.puredanger.com/java7/#switch the examples are very usefull.
Note that a "function-type" is really a type under the proposal:
{int => boolean} evaluateInt; //declare variable of "function" type
evaluateInt = {int x => x % 2 }; //assignment
I think there is still a lot of debate going in with regards to what syntax will ultimately be used. I'd actually be pretty surprised if this does make it into Java 7 due to all of that.
closures will be annoyinglly verbose if there won't be any sort of type inference... :(
Closures have some serious edge cases. I would say that Closures are a much more significant change than Generics and the later still has a number hairy edge cases.
e.g. The Java Collections libraries cannot be written/compiled without warnings.

Categories

Resources