Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Strings and best practices 3

Status
Not open for further replies.

Einstein47

Programmer
Nov 29, 2001
737
0
0
US
Hey all,

I have a pretty simple question (but it is usually the simplest questions that have the most controversial answers). Which is better:
Code:
int index = 5;
String indexStr = String.valueOf(index);
or
Code:
int index = 5;
String indexStr = index + "";
I have seen both in the code that I am maintaining (written by various contractors over the years), and I just got curious which is better or preferred. Is there a best practice for turning an int into a String?

Einstein47 (Starbase47.com)
“PI is like love - simple, natural, irrational, endless, and very important“
 
Code:
// best for readability
String indexStr = Integer.toString(index);

Code:
// best for maintainability
String indexStr = String.valueOf(index);

Code:
// kludgy and possibly slow
String indexStr = "" + index;
 
Sorry, but with the piece of code provided, the one I pointed out is the best choice, as it uses the interal string pool of the JVM.

If you want to improve the performance of your code to those levels, you need to have a context. If not, there's no possible answer.

For example, if you're planning to do that more times, maybe a StringBuffer is the way to go. If you're planning to compare to another String, maybe it's faster to convert the other String an compare as numbers ...



Cheers,
Dian
 
As a side note.

This is the code of String class

Code:
String valueOf(int i){
return Integer.toString(i, 10);
}

So you can avoid a method call, that is pretty much unimportant

Cheers,
Dian
 
Thanks for all the responses and the valuable insight.

The reason this is important is we have a utility method that we use for displaying values on JSP pages. The class is TextUtil and we have many small methods. Here is the one that got me started on this discussion:
Code:
[maroon]package[/maroon] gov.utcourts.util;

[maroon]public class[/maroon] TextUtil {

	[green]/**
	 * The default date format is "MM-dd-yyyy".
	 * This is used when a date format is unspecified.
	 */[/green]
	[maroon]public static final[/maroon] String [blue]DEFAULT_DATE_FORMAT[/blue] = [blue]"MM-dd-yyyy"[/blue];

	[green]/**
	 * used with JSP's so that you don't have nullpointers while attempting to print a field.
	 * instead of null, an empty string is returned.
	 */[/green]
	[maroon]public static[/maroon] String print([maroon]int[/maroon] param) {
		[maroon]if[/maroon] (param == 0) {
			[maroon]return[/maroon] [blue]""[/blue];
		}
		[maroon]return[/maroon] param + [blue]""[/blue];
	}

	[green]/**
	 * Used with JSPs to print Date objects with the default ("MM-dd-yyyy")
	 * date format.  If the date parameter passed-in is a null, an empty
	 * String is returned.
	 * 
	 * @param date The Date object to format.
	 * @return A formatted Date object with the default date format.
	 */[/green]
	[maroon]public static final[/maroon] String printDate(Date date) {
		[maroon]return[/maroon](printDate(date, TextUtil.[blue]DEFAULT_DATE_FORMAT[/blue]));
	}

	[green]/**
	 * Used with JSPs to print Date objects with the provided date
	 * format.  If the date parameter passed-in is a null, an empty
	 * String is returned.
	 * 
	 * @param date The Date object to format.
	 * @param format The desired format to use.
	 * @return A formatted Date object with the default date format.
	 */[/green]
	[maroon]public static final[/maroon] String printDate(Date date, String format) {
		[maroon]if[/maroon] (date == [maroon]null[/maroon])
			[maroon]return[/maroon]([blue]""[/blue]);
		
		SimpleDateFormat sdf = [maroon]new[/maroon] SimpleDateFormat(format);
		[maroon]return[/maroon](sdf.format(date));
	}
}
This way we don't display 0 (zero) on JSPs. This method is invoked all over the place. We also have similar methods for doubles, longs, boolean, Date (as shown), and even Strings (so instead of printing "null" we return an empty string (""). With these utility methods being used so much, I wanted to make sure they are the most efficient possible.

Thanks again all for your help.

Einstein47 (Starbase47.com)
“PI is like love - simple, natural, irrational, endless, and very important“
 
With these utility methods being used so much, "

Used more than a tenthousand times per second? I bet you won't measure much of a difference - when it comes to hotspot optimization, maybe all codes will lead to the same instrucitons.

But your comment is misleading:
Code:
    /**
     * used with JSP's so that you don't have nullpointers while attempting to print a field.
     * instead of null, an empty string is returned.
     */
    public static String print (int param) {
        if (param == 0) {
            return "";
        }
        return param + "";
    }
An int may never be null, because it's not an object.

Your test (param == 0) is something completly different, since it tests for a value of 0, not for a null reference.

don't visit my homepage:
 
I must agree with Stefan: there's no point on looking for performance issues at this level, even if you're using the utility method 10.000 times per second.

If you're really concerned with that, you should use someting like

Code:
<%=(i==0?"":Integer.toString(i)>

as it wouldn't do the static method call.

Btw, I'm not sure if this would work.

Code:
<%=(i==0?"":i>


Cheers,
Dian
 
Hey Stefan - you are very correct - the bane of having contractors is the JavaDoc is the last thing to be done, and is usually just copy/paste. I will update this method so the JavaDoc is correct and not misleading.

I appreciate everyone's help here. It is what I enjoy so much from Tek-Tips, real community instead of purchased friendship.

Einstein47 (Starbase47.com)
“PI is like love - simple, natural, irrational, endless, and very important“
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top