.NET String vs StringBuilder

by Abe Miessler 8. December 2009 03:44

A common mistake made by new programmers is to not utilize the StringBuilder class in the .Net framework.  To begin understanding when we should use StringBuilder let's first look at some of the inner workings of strings.

The most important thing to know about strings is that they are immutable.  That is, once you have created a string you can never change it.  It will never get longer, shorter or have any of its characters changed.  This is a difficult concept for many people to understand.  Lets look at the code below:

string Name = "Abe";

Name = Name + "miester";

While it might appear that you are actually just adding "miester" to the end of "Abe" in order to update the existing string what is happening in the background is actually much different.  When you assign the new value to the Name variable two entirely new strings are created.  There are now actually three strings in memory: "Abe", "miester" and "Abemiester".  The strings "miester" and "Abe" are no longer needed and the garbage collector will reclaim their memory at the next collection.

Now that we have an idea of how strings work lets look at a situation that could be improved by the use of the StringBuilder class.  Lets look at the code below:

 

    string letsCount = "Let's count! ";

    for(int i=; i< 100; i++)

    {

         letsCount += i + ", ";

    }

    Console.WriteLine(letsCount);

 

The above code will create a string that counts from 0 to 100.  Unfortunately, since we are using the string class, a new string will be created on the heap every iteration.  To avoid this we can use the StringBuilder class.

The StringBuilder class is provided as a means to dynamically construct a string in an efficient manner.  A StringBuilder object represents a string as an arrary of Char structures, each Char can have it's value changed and the array can be shrunk.  If the string grows beyond the allocated array of characters, StringBuilder automatically creates a new, larger array, copies the contents over, and begins using the new array.  It should be noted that dynamically growing your StringBuilder contents hurts performance so you should do your best to set a good initial capacity.  When you are working with a String who's value changes frequently this is much more efficient.  Lets look at the code below:

    using System.Text;

    StringBuilder letsCount = new StringBuilder("Let's count! ", 150); //Initialize the string to "Let's count!" and set the initial length to 150

    for(int i=; i< 100; i++)

    {

         letsCount..AppendFormat("{0}, ",i);

    }

    Console.WriteLine(letsCount.ToString());

 

This method is much more efficient because we are not creating a new string on every iteration.  In situations where you are dynamically adding to a string you should try to use this method whenever possible.

 

Update:

After talking with some of the folks at StackOverflow.com I found out that the fastest way to do string appends is actually to use the String Join method.  While StringBuilder does offer an improvement, Join performs even better.  Take a look at this post for more details on why.

 

Tags: , , ,

ASP.NET | StringBuilder

ASP.NET MVC "Hello World" tutorial.

by Abe Miessler 6. December 2009 22:12

After listening to one of my coworkers rave about how wonderful MVC was for the last week I decided it was time to cut my teeth with the ASP.NET MVC 1.0 framework and find out for myself if it was really all it was cracked up to be.  Below you will find step by step instructions to creating your first basic ASP.NET MVC “Hello World” application.


To begin you must download the ASP.NET MVC framework which can be found here.


Once this has installed open Visual Studio and create a new ASP.NET MVC Web Application:



Next you will be asked if you would like to create Unit Tests for this application.  Since this is beyond the scope of this tutorial we will select “No” and continue.


We now have our base MVC Project and we will begin adding functionality.  Let’s start by adding a model to the project.  To do this right click on the “Models” folder and select Add->Class and name it “Person.CS”.



In our new class we will create a new string member called “Name”.



Next we will add a controller class called HelloWorldClass.cs.  To do this, right click on the “Controls” folder and click “Add New Item”.  In the Add New Item dialog box select “MVC Controller Class” and name it “HelloWorldController.cs”.  As you continue through this tutorial you will probably notice that this Controller contributes little to the project.  While we could get away without having a Controller for a project that is this simple, I wanted to introduce the concept to illustrate how Models, Views and Controllers interact with one another.



Now we will reference the Person model from the HelloWorldController and add a function called “SayHello”.  When you are done your HelloWorldController should look like this:



The “HelloWorldController” now has a function that will accept a string called “username” and return that to the View.  In order to complete this process we must now create a View that will display what is returned by the “SayHello” function.  To add our view you must first right click on the “Views” folder and add a new folder called “HelloWorld”.  Once created right click the folder and select Add->New Item.  In the “Add New Item” dialog select “MVC View Content Page” and name it “Greet.aspx”.



Next you will be prompted to select a master page.  The default one will work fine for our project so just click ok.



Now we will add some simple code to display a greeting to whatever name is in ViewData[“PersonsName”].  When you are finished your page should look like this:



The last step we need to take is also the step that I found the most confusing.  In the global.asax file we must update the RegisterRoutes method to map to our new page with the appropriate parameters.  For simplicitiy sake I will just provide the code to enter in but if you would like to see Routing explained I have a post that goes into more detail here.


To setup routing for this project we will add the following code BEFORE the default route that is already in the RegisterRoutes method.


            routes.MapRoute(

                "HelloWorld",

                "HelloWorld/{action}/{userName}",

                 new

                 {

                     controller = "HelloWorld",

                     action = "SayHello",

                     userName = "Mystery Man"

                 }

            );


When you done it should look like this.



Now it is time to see the fruits of our labor.  Run your project for the first time.  You should see the following page:



Now you must enter a URL that will be routed to our newly created page.  To do this enter “HelloWorld/Greet/Abe” after the URL above.  When you do you should see the page below:



Congratulations! You have created your first ASP.NET MVC page!

 

Conclusions:

While I had originally setout to find advantages of MVC vs Forms I feel that this tutorial really only served to introduce me to using the MVC framework.  Now that I am familiar with MVC I hope to do another tutorial that demonstrates (or dosn't) the advantages that MVC has over Forms.  Stay tuned...

Tags: , , ,

Blog | ASP.NET | MVC

First Post!

by Abe Miessler 2. December 2009 04:22

My name is Abe Miessler and this is my website.  I am a software engineer specializing in the .NET framework and SQL Server.  I've created this site as a motivation for me to learn more about the technologies that I am comfortable with, learn more about technologies that I know little or nothing about and maybe even help a person or two along the way.  Welcome.

Tags:

Powered by BlogEngine.NET 1.6.0.0