Integer.toString(int);
and
String.valueOf(int);
Which one among the above two methods is the efficient way of converting an int to String?
Thanks in advance.
String.valueOf calls Integer.toString, so I guess you could argue that Integer.toString is marginally more efficient.
EDIT: With a modern compiler the calls will be inlined so there should be no difference at all between the two. With an ancient compiler the difference should still be negligible.
I think that the String.valueOf() method was just provided for the purpose of flexibility, Since the purpose is closely related with String class(in fact for the conversion to String). While the (Integer/Float/etc).toString() method is the authentic method for the purpose of String conversion. You can refer them as slightly overloaded method.
Actually it doesn't matter which method you use. But I think Integer.toString(int); is more efficient because, String.toString(int); is internally calling the same method.
Related
I'm working on a JSONObject with multiple sub-JSONObjects.
Here is the way I fill the content :
myJson.getJSONObject(CAT_NAME).put(VAR_NAME, var)
.put(VAR_NAME2, var2)
.put(...);
A friend told me that it is a very bad practice to use "nested function/method calls" and that I should do it this way :
myJson.getJSONObject(CAT_NAME).put(VAR_NAME, var);
myJson.getJSONObject(CAT_NAME).put(VAR_NAME2, var2);
myJson.getJSONObject(CAT_NAME).put(...);
From my view, my way is more like an chained method call than a nested one.
And I don't like the second way because it force the program to get the same object again and again when the put() method already returns it.
Is my case is a "nested function calls" case ?
Is this dangerous or bad for any reason ? And what are those reasons ?
edit : I don't feel like my question is duplicated. The other question involves chained methods but it mainly talks about c# interfaces.
Is my case is a "nested function calls" case ?
No that is method chaining (Builder pattern).
Is this dangerous or bad for any reason ?
No. Your friend is wrong. Not at all bad practice in your case. It's quite Ok since you are building a Json.
Using method chaining will actually be more efficient than the alternative you provided because myJson.getJSONObject(..) is only called once in the first case, whereas you call it many times in the second. There is a much more significant cost for calling getJSONObject(..) than there is for reusing the original object returned by it.
The correct way to accomplish this without using method chaining would be more like this:
JSONObject obj = myJson.getJSONObject(CAT_NAME);
obj.put(VAR_NAME, var);
obj.put(VAR_NAME2, var2);
obj.put(...);
Personally, I prefer to not use method chaining because I think it looks better, but ultimately it's your preference and the code here would have basically the same performance as your first chunk of code.
He PROBABLY considers it bad because it can be less readable (but that's a personal opinion and depends a lot on code formating, how well someone understands the specific APIs, is familiar with the concept of method chaining, etc. etc.).
It's certainly not a generally bad thing to do though. In fact a lot of APIs work exactly like that. Just look at StringBuilder in the Java standard API as a very commonly used example.
As others already pointed out it's potentially more performant (depending on how the called methods are implemented) as well, but that's not a given.
Given a java.lang.reflect.Method object, is there anyway to determine whether the method is purely functional (i.e., given the same input, it will always produce the same output and it is stateless. In other words, the function does not depend on its environment)?
No, there's no way to do it.
Reflection does not allow you to inspect the actual code behind the method.
And even if that where possible, the actual analysis would probably be ... tricky, to say the least.
No there is no way to do that with reflection or any other mechanism.
The developer knows if the method is functional. For example, Spring has a #Cacheable annotation that gives a hint to the application that the method is functional and can therefore cache the result for a given set of arguments. (Spring will wrap your object in a proxy that provides the caching behavior.)
is there anyway to determine whether the method is purely functional(ie., given the same input, it will always produce the same output
I know it's now what you've asked for, but Unit Tests may help you with this.
No. Reflection can not read the byte code of the method. So you can't really tell what a method does or even what other classes it uses.
Reflection will not help you here. If you really want to define it at run time, you can try to use javap -c classname.class. But it would be better to avoid such a hacks.
This question was prompted after reading Joshua Bloch's "Effective Java". Specifically in Item #10, he argues that it is bad practice to parse an object's string representation and use it for anything except a friendlier printout/debug. The reason is that such a use "is error-prone, results in fragile systems that break if you change the format".
To me it looks like Guava's Ordering.usingToString() is a spot on example of this. So is it bad practice to use it?
Well, if the sorting is only used for deciding in which order to display things to a user, I'd argue it's part of "friendlier printout/debug".
If, however, your codes correctness depends on the ordering, then I'd argue that it's indeed a bad idea to depend on toString.
As the author of that method, I would agree: it's really just a crutch. For those "look, I just need an Ordering<Object>, dammit" cases. It should probably be removed, since you can get its behavior with Ordering.onResultOf(Functions.toStringFunction) anyway.
If your program ever used the toString() for lexical sorting using natural ordering in such a way that program execution depends on it, then it would be wise to override the default toString() of the class that extended. You should in that case make the toString() method final and clearly document that it is used for ordering.
It would however be much better to create another method returning a String and create an ordering depending on that result, possibly by creating a specific Comparator to do the sorting. See for instance the final method name() used for enumerations in Java. In general it creates the same String as toString() but it is still possible to perform ordering with it even if toString() has been overridden.
If you use the last method, then the Ordering.usingToString() would not be of much use of course.
There are some obvious cases where it actually makes sense like StringBuffer etc. Obviously it doesn't make sense for most "business" classes to depend on toString().
I have a class called Zebra (not her actual name). Zebra overrides the toString method to provide her own convoluted obfuscated stringification.
Which is more efficient to stringify an instance of Zebra? Presuming that I have to do this stringification millions of times per session.
zebra.toString()
""+zebra
static String BLANK (singleton)
BLANK+zebra (multiple executions).
Where the value of zebra is not assured to be the same.
I am conjecturing that the answer could be - no concern: the compiler makes them all equivalent. If that is not the answer, please describe the instantiation process that makes them different. (2) and (3) could be the same, since the compiler would group all similar strings and assign them to a single reference.
Normally, I do ""+zebra because I am too lazy to type zebra.toString().
ATTN: To clarify.
I have seen questions having been criticised like "why do you want to do this, it's impractical" If every programmer refrains from asking questions because it has no practical value, or every mathematician does the same - that would be the end of the human race.
If I wrote an iteration routine, the differences might be too small. I am less interested in an experimental result than I am interested in the difference in processes:
For example, zebra.toString() would invoke only one toString while, "+zebra would invoke an extra string instantiation and and extra string concat. Which would make it less efficient. Or is it. Or does the compiler nullify that.
Please do not answer if your answer is focused on writing an iterative routine, whose results will not explain the compiler or machine process.
Virtue of a good programmer = lazy to write code but not lazy to think.
Number 1 is more efficient.
The other options create an instance of StringBuilder, append an empty string to it, call zebra.toString, append the result of this to the StringBuilder, and then convert the StringBuilder to a String. This is a lot of unnecessary overhead. Just call toString yourself.
This is also true, by the way, if you want to convert a standard type, like Integer, to a String. DON'T write
String s=""+n; // where "n" is an Integer
DO write
String s=n.toString();
or
String s=String.valueOf(n);
As a general rule, I would never use the + operator unless it is on very small final/hard-coded strings. Using this operator usually results in several extra objects in memory being created before your resulting string is returned (this is bad, especially if it happens "millions of times per session").
If you ever do need to concatenate strings, such as when building a unique statement dynamically (for SQL or an output message for example). Use a StringBuilder!!! It is significantly more efficient for concatenating strings.
In the case of your specific question, just use the toString() method. If you dont like typing, use an IDE (like eclipse or netbeans) and then use code completion to save you the keystrokes. just type the first letter or 2 of the method and then hit "CTRL+SPACE"
zebra.toString() is the best option. Keep in mind zebra might be null, in which case you'll get a NullPointerException. So you might have to do something like
String s = zebra==null ? null : zebra.toString()
""+zebra results in a StringBuilder being created, then "" and zebra.String() are appended separately, so this is less efficient. Another big difference is that if zebra is null, the resulting string will be "null".
If the Zebra is Singleton class or the same instance of zebra is being used then you can store the result of toString in Zebra and reuse it for all future calls to toString.
If its not the case then in implementation of toString cache the part which is unchanges everytime in constructing String at one place, this was you can save creating some string instances every time.
Otherwise I do not see any escape from the problem you have :(
Option 1 is the best option since every option calls the toString() method of zebra, but options 2 and 3 also do other (value free) work.
zebra.toString() - Note that this calls the toString() method of zebra.
""+zebra - This also calls the toString() method of zebra.
static String BLANK; BLANK+zebra; - This also calls the toString() method of zebra.
You admit "I'm lazy so I do stupid stuff". If you are unwilling to stop being lazy, than I suggest you not concern yourself with "which is better", since lazy is likely to trump knowledge.
Since the object's toString method will be invoked implicitly in cases where it is not invoked explicitly, a more "efficient" way doesn't exist unless the "stringification" is happening to the same object. In that case, it's best to cache and reuse instead of creating millions of String instances.
Anyway, this question seems more focused on aesthetics/verbosity than efficiency/performance.
If you want to know things like this you can code small example routines and look at the generated bytecode using the javap utility.
I am conjecturing that the answer could be - no concern: the compiler makes them all equivalent. [...] Normally, I do ""+zebra because I am too lazy to type zebra.toString().
Two things:
First: The two options are different. Think about zebra being null.
Second: I'm to lazy to do this javap stuff for you.
I have a method which takes String argument. In some cases I want to pass int value to that method. For invoking that method I want to convert int into String. For that I am doing the following:
aMethod(""+100);
One more option is:
aMethod(String.valueOf(100));
Both are correct. I don't know which is appropriate? Which gives better performance?
Mostly this is happen in GWT. In GWT for setting size of panels and widgets I want to do this.
Using + on strings creates multiple string instances, so using valueOf is probably a bit more performant.
Since you're mostly using it in GWT, I'd go with the ""+ method, since it's the neatest looking, and it's going to end up converted to javascript anyway, where there is no such thing as a StringBuilder.
Please don't hurt me Skeet Fanboys ;)
Normally you'd use Integer.toString(int) or String.valueOf(int). They both return the same thing, and probably have identical implementations. Integer.toString(int) is a little easier to read at a glance though, IMO.
I'd assume that this:
aMethod(""+100);
turns into this by the compiler:
aMethod(new StringBuilder("").append(String.valueOf(100)).toString());
So the option of calling the String.valueOf directly is probably the better choice. You could always compile them and compare the bytecode to see for sure.