Not confident about whether this will be downvoted or closed... I need expert opinion on this.
The context is in our application, we have written code like :
//countryId is an integer, searchCity() expects two String parameters
loadCity(countryName , countryId + "");
Will it make any difference if I change (I am being forced to do so) the call like :
loadCity(countryName, String.valueOf(countryId));
Or,
loadCity(countryName, Integer.toString(countryId));
Will this make any difference in sense of performance?
For the example you have given, the answer will really depend on the type of 'integer' you are using.
loadCity(countryName , countryId + "");
For an Integer object this is equivelent to :
loadCity(countryName, countryId.toString() + "");
Whereas for an int primitive, this code is equivelent to :
loadCity(countryName, String.valueOf(countryId) + "");
In either case, as ArjunShankar pointed out there is a good chance that the compiler has optimised your code anyway. So if your question is 'do I go back and refactor all my code?', then I would say 'don't sweat the small stuff'. But in the future use a more conventional approach to avoid the down votes.
I'd say the main difference is readability. There's no use in micro-benching here. IMHO String#valueOf reads the best.
From the docs of String.valueOf
"The representation is exactly the one returned by the Integer.toString method of one argument."
I would use String.valueOf because you can use it on more then just Integers, i.e. you don't have to know whether you have an int, double, bool, etc....
They are same.... because
the method String.valueOf(int i) implicitly calls Integer.toString(i, 10);
A search on both methods informed me all of these are equivalent:
String.valueOf(countryId)
Integer.toString(countryId)
countryId.toString() //Only if countryId is an Integer
Because they all call:
Integer.toString(countryId, 10)
The only difference is if you wish to use a different radix, ie:
Integer.toString(countryId, radix)
Personally I think countryId.toString() reads better when using an Integer. Otherwise Integer.toString(countryId) is the way to go. But that is just my personal opinion. Performance-wise you should use Integer.toString(countryId, 10).
I think that adding an empty string to an int to convert it to a String is a bad practice.
Related
In a code base I'm working with I'm seeing this idiom being used.Can someone explain it for me?
new String("" + number) // `i` is an instance of Integer
For some context, this is approximately what the method looks like:
public String someMethod(String numberString) {
Integer number = new Integer(numberString);
// other stuff happens...
return new String("" + number);
}
It's most likely nothing but an inexperienced Java programmers attempt at converting a number to a String.
Whether converting numbers to Strings using "" + number is good practice is debateable. I for one find String.valueOf(number) to be more clear (although it's semantically equivalent).
It's completely unnecessary to wrap the result in new String(...) unless you (for some unimaginable reason) really need a new string, i.e. one that's referentially distinct from other strings.
This ideom is the easiest way of converting any primitive or Object type to a string.
It is quite easy: Typing "" + number is less work than typing String.valueOf(number) (or Integer.toString(number). The latter is the usual way of transforming an int into a String. Which one is clearer and to be preferred is a matter of taste. You will find advocates for both versions.
But note three things:
Calling String.valueOf(number) is faster, because "" + number will become a string concatenation, it will be compiled to
new StringBuilder().append("").append(number).toString()
However, unless this statement is in a hot place in your code, the difference will not matter at all. Even in a hot place, the difference might still be negligible
Simply calling number.toString() is also an option since number is a boxed integer. However, if number is null, this will trigger a null pointer exception so be careful!
The last line of your example, i.e., new String("" + number); is simply crap! It wraps the result into a newly built string. This creates an unnecessary copy and costs precious extra keystrokes. It also generates unnecessary boilerplate noise in your code. This last line compiles to:
new String(new StringBuilder().append("").append(number).toString())
That is quite some work for transforming int to String. You first create a StringBuilder, then a built String and then a copy of this built String. This creates three objects instead of one.
This idiom is used to automatically convert the integer number to a string.
The String constructor expects an argument of type String. The expression new String(number) would not compile. Concatenting an empty string is a little trick to turn the Integer into a String.
You could of course use new String(number.toString()) or String.valueOf(number) instead.
Note: As Jon Skeet mentions in the comments there is no need to use new Sring() at all. You could just return number.toString(); or return String.valueOf(number)
is there any difference in performance between these two idioms ?
String firstStr = "Hello ";
String secStr = "world";
String third = firstStr + secStr;
and
String firstStr = "Hello ";
String secStr = "world";
String third = String.format("%s%s",firstStr , secStr);
I know that concatenation with + operator is bad for performance specially if the operation is done a lot of times, but what about String.format() ? is it the same or it can help to improve performance?
The second one will be even slower (if you look at the source code of String.format() you will see why). It is just because String.format() executes much more code than the simple concatenation. And at the end of the day, both code versions create 3 instances of String. There are other reasons, not performance related, to use String.format(), as others already pointed out.
First of all, let me just put a disclaimer against premature optimization. Unless you are reasonably sure this is going to be a hotspot in your program, just choose the construct that fits your program the best.
If you are reasonably sure, however, and want to have good control over the concatenation, just use a StringBuilder directly. That's what the built-in concatenation operation does anyway, and there's no reason to assume that it's slow. As long as you keep the same StringBuilder and keep appending to it, rather than risking creating several in a row (which would have to be "initialized" with the previously created data), you'll have proper O(n) performance. Especially so if you make sure to initialize the StringBuilder with proper capacity.
That also said, however, a StringBuilder is, as mentioned, what the built-in concatenation operation uses anyway, so if you just keep all your concatenations "inline" -- that is, use A + B + C + D, rather than something like e = A + B followed by f = C + D followed by e + f (this way, the same StringBuilder is used and appended to throughout the entire operation) -- then there's no reason to assume it would be slow.
EDIT: In reply to your comment, I'd say that String.format is always slower. Even if it appends optimally, it can't do it any faster than StringBuilder (and therefore also the concatenation operation) does anyway, but it also has to create a Formatter object, do parsing of the input string, and so on. So there's more to it, but it still can't do the basic operation any faster.
Also, if you look internally in how the Formatter works, you'll find that it also (by default) uses a StringBuilder, just as the concatenation operation does. Therefore, it does the exact same basic operation -- that is, feeding a StringBuilder with the strings you give it. It just does it in a far more roundabout way.
As described in this excellent answer , you would rather use String.format, but mainly because of localization concerns.
Suppose that you had to supply different text for different languages, in that case then using String.format - you can just plug in the new languages(using resource files). But concatenation leaves messy code.
See : Is it better practice to use String.format over string Concatenation in Java?
This question already has answers here:
Which is better/more efficient: check for bad values or catch Exceptions in Java
(11 answers)
Closed 9 years ago.
I have seen two styles for checking whether a variable is a valid integer in Java. One by doing an Integer.parseInt and catching any resulting exception. Another one is by using Pattern.
Which of the following is better approach?
String countStr;
int count;
try {
count = Integer.parseInt(countStr);
} catch (Exception e) {
//return as the variable is not a proper integer.
return;
}
or
String integerRegex = "([0-9]{0,9})";
if (countStr.isEmpty() || !Pattern.matches(integerRegex, countStr)) {
//return as the variable is not a proper integer.
return;
}
My question here is, is doing an Integer.parseInt() and catching an exception for validation a standard way to validate an int? I admit that my regex is not perfect. But is there any built-in methods available in Java for validation of int? Actually isn't it better to do some validation instead of simply catching the exception?
Using the approach above is better as it considers all types of possible errors and handles all cases. For instance what you have written will not parse negative numbers correctly.
It only makes sense to write your own verifier if you want to validate a given subset of all integers.
A general advice: don't re-invent the wheel unless you have strong reasons to do so.
There's a really good reason to not go with the second approach if you actually want to check if the given string can be represented as a 32bit integer and not just that it represents an integer in the mathematical sense.
I'm sure we all agree that 2147483648 (2**31 for those paying attention) is a perfectly fine integer, but it's only one of infinitely many numbers for which the two options will give different results. So if you want to check if you can represent a string as a 32bit integer use the parseInt method, if you just want to see if it's an integer go with the regex.
PS: That said don't catch Exception, but the correct NumberFormat exception instead..
These two function serve different purposes. If you just want to make sure that the string cotains a particular pattern, then use the second approach. If you need to convert it, then you should can parseInt() In this case it wouldn't make sense to check it and convert it as well.
However, if you have specific requirements for the number, then you may have to check it first regardless, because parseInt() may not always throw an exception if it can parse something which still doesn't fit your requirement.
If you just validat an Integer, I think the second way is better.
These two methods both will work fine, but obviously different focus. The former focuses on the transformation itself, while the latter is clearly more attention checked. And you want to check a number is, so I think the second method is better. Also, I think, some of the second method more readable, allowing code maintenance is a clear to see, where the logic is in checking the validity of a number instead of a string into a number.
When needing to convert a primitive to a String, for example to pass to a method that expects a String, there are basically two options.
Using int as an example, given:
int i;
We can do one of:
someStringMethod(Integer.toString(i));
someStringMethod(i + "");
The first one is the "formal" approach, and the second one seems somewhat of a "hack".
It's certainly a lot less code and easier to read the "hack" IMHO.
But is it "good" coding style to use the "hack"?
The best way to convert * to String is to use:
String.valueOf(x)
it works with primitive types, wrapper classes and Object who do implement toString().
where x is any kind of primitive or object. If it is null it returns the string 'null'.
The reason why this is best, is because using "+" operand implies String concatenation, plus the "" implies String instantiation. If you decompile a class using ""+something you'll see the compiler translate that to multiple operations.
"" concatenation result is the same as String.valueOf() but it is a little bit more expensive.
The performance difference is probably negligible, but good programmers don't write '"" + something' to convert something to a String when there is a better way, which happens to be the correct way :).
For arrays, have a look at Arrays.toString() and -better- Arrays.deepToString()
But is it "good" coding style to use the "hack"?
Sometimes syntactic hack make the code better. But the case above, is not really one of those cases.
"" concatenation not considered good code.
An example of a useful syntactic hack is the double brace instantiation:
List<String> list = new ArrayList<String>() {{
add("foo");
add("bar");
add("baz");
}};
instead of
List<String> list = new ArrayList<String>();
list.add("foo");
list.add("bar");
list.add("baz");
The ""+something is more a code smell than a hack that improve readability; anybody with some experience would think to a Java developer who lack some knowledge of the API and the language.
Other interesting "hacks" are fluent APIs (like Mockito), dsl, or things like lambda4j, which is quite an hack.
It's not a good idea, but it's not going to be very harmful.
In both examples Integer.toString() is being called by the JVM (even if not directly in the first case).
In the second example, the JVM possibly constructs two strings and then produces the result of the concatenation. Depending on optimizations this may result in 0, 1 or 2 extra strings to garbage collect.
From a code writing perspective, the third is shorter, but also possibly less transparent as to what is happening.
The problems with the second approach in readability follow:
int i = 1, j = 2;
someStringMethod(i + j + "" + i + j + "");
Produces:
someStringMethod(312);
and not
someStringMethod(33);
When strings are formed using + sign, jvm will create a intermediate string/stringbuffer object to carry out trasnformation, which is not the optimum way.
Also, + sign is left associative,so when used in expressions like ""+1+2 will result in 12 and not "3".So it's better to use String.toValue() or Type.toString().
Concatenation symbol in java is +.
So you convert the result of (i + "") to String because you concat an empty string to a number in your example code.
The two ways are good but I normally use String.valueOf(x);
I just bumped into this little problem and I wanted the input of other people on this
I was wandering what was the best solution to convert a String to an int
(int)(float)Float.valueOf(s)
or
Float.valueOf(s).toInt()
s is a String inputed from a textfield so I can not guarantee that it is necessarily an int
my instincts is that the double cast is ugly and should be avoided
Your input?
Your requirements are unclear:
If you are expecting an integer and don't want to allow the user to enter a number with a decimal point in it, simply use Integer.valueOf(String) or Integer.parseInt(String) and catch the NumberFormatException.
If you want to allow numbers with decimal points, then use Float.valueOf(String) or Float.parseFloat(String).
If you simply want to truncate the float to an int then either Float.intValue() or two casts are equivalent. (The javadoc for intValue explicitly states this.)
If you want to round to the nearest int, use Math.round() instead of a cast.
You should catch NumberFormatException whatever approach you take, since the user could enter rubbish that is not a valid base-10 number (with or without a decimal point) ... or that exceeds the bounds of the number type.
(I suppose that you could use a regex or something to check the String before trying to convert it, but it is simpler to just let the exception happen and deal with it. The exception efficiency issue is unlikely to be a practical concern in this use-case.)
On your original question as to whether intValue() is better than two casts: it is a matter of style. The two approaches do the same thing ... according to the javadoc. It is possible that one will be slightly more efficient than the other, but:
that shouldn't be a concern for your use-case, and
the only way to know for sure would be to profile the two alternatives on your execution platform ... and frankly it is not worth the effort.
You should use Integer.valueOf(..), and catch the NumberFormatException (if the string cannot be parsed as an integer).
Integer.parseInt(string) would be best
int x = Integer.parseInt(s);
Would be best to check if the string is an int before calling this.
As others pointed out, its just matter of style not performance... but if you are worried about performance you should validate the text field data in browser itself by javascript using a regex
^[0-9]*$
which would allow only integers to be submitted to your back-end code and hence improving performance by avoiding one network trip. Still you should validate the data in back-end, for that you can use
Integer.parseInt(String s) throws NumberFormatException