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 IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

The cost of Strings

Status
Not open for further replies.

Garp

Programmer
Mar 17, 2001
6
CZ
Hi All,
can somebody make me clear this way? :) How it is possible to write better ?

pulbic class Log
{
public static void log(String s, String t)
{
System.out.println("heading" + s + "trailer" + t);
}
}



The cost of Strings: The String concatenation operator + looks innocent but involves a lot
of work. The compiler can efficiently concatenate constant strings, but a variable string
requires considerable processing. For example, if s and t are String variables:
System.out.println("heading" + s + "trailer" + t);
this requires a new StringBuffer, appending arguments, and converting the result back to a
String with toString( ). This costs both space and time. If you're appending more than one
String, consider using a StringBuffer directly, especially if you can repeatedly reuse it in a
loop. Preventing the creation of a new StringBuffer on each iteration saves the object
creation time of 980 seen earlier. Using substring( ) and the other String methods is usually
an improvement. When feasible, character arrays are even faster. Also notice that
StringTokenizer is costly because of synchronization.


THX
Garp
 
How about you showed us how to do it instead of showing us how not to do it? Your arguments seem sound, I just would remember better with an example and you wouldn't have to spend so much time explaining it.
 
Thanks Dan,
but in this (how to do it instead of showing us how not to do it? ) is my problem :) I know how not to do it but ....my question and modest request :) sound

how add String together without waste of time.

maybe is possible something like this

pulbic class Log{
MyStringBuffer sb = new MyStringBuffer();

public static void log(String s, String t) {
sb.emptyMySB();
sb.append("heading");
sb.append(s);
sb.append("trailer");
sb.append(t);
System.out.println(sb.toString());
}
}

but i don't think that is "elegant.."
please can someGuru help me
THX
G.
 
Here's how I might do it:

pulbic class Log
{
public static void log(String s, String t)
{
MyStringBuffer sb = new MyStringBuffer("heading");
sb.append(s).append("trailer").append(t);
System.out.println(sb.toString());
}
}

that looks pretty enough to me. what do you think?
 
Hmm, yes ..but above has been writen

Preventing the creation of a new StringBuffer on each iteration saves the object
creation time of 980 seen earlier


your example unsolved not thing :(


 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top