Improving String Management with StringBuilder

dotnetlogo
Strings are immutable. In other words, a string cannot be changed once it is assigned. When you append a string to an existing string, the .NET Framework actually creates a new string containing the original string and the appended string. If you are thinking that this takes extra processing time, you are correct.

String concatenation has been optimized, so minimal amounts of concatenation won’t have a noticeable impact on performance. The impact is noticeable if you are appending a lot of strings; for example, if you are appending many strings to build ASP.NET page contents or to build message text.

string sMessage = “This is a message”;
sMessage += ” for user ”
sMessage += sUserName;

In this example, it appears that an sMessage string is created, and then additional strings are appended to sMessage, modifying the original string. But that is not what is actually happening. In the first line of the example, the string is created and assigned the default value (“This is a message”). In both the second and third lines of the example, the sMessage string is destroyed (marked for deletion by the garbage collector), and a new sMessage string is created to contain the original string plus the appended string.

If the string concatenation is all done as one assignment, the string is not destroyed between concatenations, and there is no performance impact.

string sMessage = “This is a message” + ” for user ” + sUserName;

However, when concatenating many long strings or building entire ASP.NET page contents using concatenation, appending all of the strings with one assignment may not be practical (or easily readable).

To minimize the impact of string concatenation on performance when you are concatenating many strings, consider using the StringBuilder class. The StringBuilder class creates a string-like object that can be changed. When you have made all of the necessary changes to the string, you can convert the StringBuilder class value to an actual string.

using System.Text;
StringBuilder sbMessage = new StringBuilder(“This is a message”);
sbMessage.Append(” for user “);
sbMessage.Append(sUserName);
string sMessage = sbMessage.ToString();

This sample code creates an instance of the StringBuilder class. It then uses the Append method of the StringBuilder class to append text to the StringBuilder. When all of the concatenations are done, the ToString method converts the StringBuilder to a String type. The StringBuilder class has other methods, such as Insert and Replace, to perform various operations on the string.

StringBuilder provides more efficient string concatenation because it creates a buffer that is large enough to contain the original string plus additional space to provide room for the string to grow. However, if the concatenations fill the extra space in the buffer, the buffer size must be extended, causing another performance hit.

Use the EnsureCapacity method of the StringBuilder class to further improve performance. EnsureCapacity allows you to set the size of the StringBuilder buffer to the expected size of the final string length. Then StringBuilder won’t need to expand the size of the buffer, so you’ll avoid a performance hit.

Initializing a StringBuilder object has more of a performance impact than using a string, so you don’t want to use StringBuilder if you are appending only a few strings. The generally recommended cutoff number is five. If you have more than five separate string concatenations, StringBuilder is generally more efficient than appending the strings.

If your string handling needs to perform as efficiently as possible, the only way to know for certain whether using string concatenation or StringBuilder is faster in your situation is to conduct your own performance testing.

Any time you see a lot of string concatenation in your code, consider using the StringBuilder class for better performance.

Creating a New Xml Document from Scratch in C#

dotnetlogo
To create a new XmlDocument, start by creating an XmlDocument object. The XmlDocument object contains CreateElement and CreateAttribute methods that are used to add nodes to the XmlDocument object. The XmlElement contains the Attributes property, which is an XmlAttribute-Collection. The XmlAttributeCollection inherits from the XmlNamedNodeMap class, which is a collection of names with corresponding values.
The following code shows how an XmlDocument can be created from scratch and saved to a file:

protected void Button1_Click(object sender, EventArgs e)
{ //Declare and create new XmlDocument XmlDocument xmlDoc = new XmlDocument();
XmlElement el;
int childCounter;
int grandChildCounter;
//Create the xml declaration first
xmlDoc.AppendChild(
xmlDoc.CreateXmlDeclaration(“1.0”, “utf-8”, null));
//Create the root node and append into doc
el = xmlDoc.CreateElement(“myRoot”);
xmlDoc.AppendChild(el);
//Child Loop
for (childCounter = 1; childCounter <= 4; childCounter++)
{
XmlElement childelmt;
XmlAttribute childattr;
//Create child with ID attribute
childelmt = xmlDoc.CreateElement(“myChild”);
childattr = xmlDoc.CreateAttribute(“ID”);
childattr.Value = childCounter.ToString();
childelmt.Attributes.Append(childattr);
//Append element into the root element
el.AppendChild(childelmt);
for (grandChildCounter = 1; grandChildCounter <= 3; grandChildCounter++)
{
//Create grandchildren childelmt.AppendChild(xmlDoc.CreateElement(“GrandChild”));}}
//Save to file
xmlDoc.Save(MapPath(“XmlDocumentTest.xml”));
}

This code started by creating an instance of an XmlDocument. Next, the XML declaration is created and placed inside the child collection. An exception is thrown if this is not the first child of the XmlDocument. The following is the XML file that was produced by running the code sample:

<?xml version="1.0" encoding="utf-8"?>
<myRoot>
<myChild ID="1">
<GrandChild />
<GrandChild />
<GrandChild />
</myChild>
<myChild ID="2">
<GrandChild />
<GrandChild />
<GrandChild />
</myChild>
<myChild ID="3">
<GrandChild />
<GrandChild />
<GrandChild />
</myChild>
<myChild ID="4">
<GrandChild />
<GrandChild /> <GrandChild /> </myChild></myRoot>

kick it on DotNetKicks.com

Vertical Text Scroller in Javascript

Well the task is to create a vertical text scroller.

It can be done using the javascript code.

Let me explain the process:

  • First of all lets make the form scrolling. So,In the html form do the following add the following attributes to the body tag onMouseover="scrollspeed=0" onMouseout="scrollspeed=current" OnLoad="NewsScrollStart();"
  • And the javascript functions used above are as follows:
    <script language="JavaScript" type="text/javascript"> 
    //<!-- HIDE CODE 
    
    var scrollspeed = "1" // SET SCROLLER SPEED 1 = SLOWEST 
    var speedjump = "30" // ADJUST SCROLL JUMPING = RANGE 20 TO 40 
    var startdelay = "2" // START SCROLLING DELAY IN SECONDS 
    var nextdelay = "0" // SECOND SCROLL DELAY IN SECONDS 0 = QUICKEST 
    var topspace = "2px" // TOP SPACING FIRST TIME SCROLLING 
    var frameheight = "200px" // IF YOU RESIZE THE WINDOW EDIT THIS HEIGHT TO MATCH 
    
    
    
    current = (scrollspeed) 
    
    
    function HeightData(){ 
    AreaHeight=dataobj.offsetHeight 
    if (AreaHeight==0){ 
    setTimeout("HeightData()",( startdelay * 1000 )) 
    } 
    else { 
    ScrollNewsDiv() 
    }} 
    
    function NewsScrollStart(){ 
    dataobj=document.all? document.all.NewsDiv : document.getElementById("NewsDiv") 
    dataobj.style.top=topspace 
    setTimeout("HeightData()",( startdelay * 1000 )) 
    } 
    
    function ScrollNewsDiv(){ 
    dataobj.style.top=parseInt(dataobj.style.top)-(scrollspeed) 
    if (parseInt(dataobj.style.top)<AreaHeight*(-1)) { 
    dataobj.style.top=frameheight 
    setTimeout("ScrollNewsDiv()",( nextdelay * 1000 )) 
    } 
    else { 
    setTimeout("ScrollNewsDiv()",speedjump) 
    }} 
    
    
    
    // END HIDE CODE --> 
    </script> 
    
    
    
    
    
  • Inside the body tag create a div element with id=”NewsDiv”
  • In the code behind add labels with text per line into this div as shown below
  • ///
    /// Handles the Load event of the Page control.
    ///
    /// The source of the event.
    /// The instance containing the event data.
    protected void Page_Load(object sender, EventArgs e)
    {
    GenerateAlert();
    }
    // Private Methods (1)

    ///
    /// this method extracts the alerts and show them in a label
    ///
    private void GenerateAlert()
    {
    XmlDocument xmldoc = new XmlDocument();
    xmldoc.Load(Server.MapPath(“../XML Files/GlobalDisasters.xml”));
    XmlNodeList xmlndlst = xmldoc.GetElementsByTagName(“title”);

    for (int i = 0; i < xmlndlst.Count; i++)
    {
    lblAlert = new Label();
    string strTitle = xmlndlst[i].InnerText.ToString();
    lblAlert.Text = strTitle + “

    “;
    NewsDiv.Controls.Add(lblAlert);
    }
    }

    kick it on DotNetKicks.com