Pages
    Calendar
    <<  September 2010  >>
    MoTuWeThFrSaSu
    303112345
    6789101112
    13141516171819
    20212223242526
    27282930123
    45678910

    Last week I entered a competion that Copenhagen .NET User Group (aka. CNUG). It was very simple: Post a link to a CNUG meeting on twitter using the #CNUG hash. I didn't really think much about it and posted a link to a talk about C#4 that I intend to attend. On Thursday an email popped into my inbox and it turns out that I've won! w00t!

    The prize was a ticket to the preconference talk and a 30-day subscription to TekPub.com - pretty sweet. The guys from Umbraco has really put together a fantastic lineup of speakers. I'm going to attend Jon Galloway's (http://weblogs.asp.net/jgalloway/) MVC bootcamp, which I'm looking very much forward to. Also speaking at the preconference is Simone Chiarette (http://codeclimber.net.nz/), which has a session about extending ASP.NET MVC and Steven Sanderson (http://blog.stevensanderson.com/), which has a session about BDD, intermediate MVC and security in MVC.

    It should be great fun!

    It’s has been a while since my last post due to vacation and common laziness – but now I’m back with a fresh post. This post concerns something that almost all programmers do on a daily basis: string concatenation.

    If you’re making a lot of string concatenations, you might experience performance problems. The problem with string concatenation is that strings in .NET are immutable.  That means that you discard the old string object and create a new one containing the concatenated string. This process requires some overhead and can have implications on the performance of the program.

    As most programmers know it can be a good idea to use the StringBuilder class when you’re concatenating many times. The rule of thumb is that the speed gained in concatenating with the StringBuilder is exceeded by the overhead in instantiating the StringBuilder object, if the number of concatenating is very low. But how big is the overhead in instantiating the StringBuilder object? And how many concatenations does it require for the StringBuilder to outperform the normal concatenation?

    The StringBuilder uses an array to store the strings and the joins the strings when the ToString() method is called. But what if you use a string array yourself and calls the Join() method when all the strings have been added – will the normal string array outperform the StringBuilder?

    To shed some light on this matter I designed some tests. I decided to test how long it took to make X concatenations and if made a difference how long the text string was.  This is the code I used:

    Imports System.IO

    Imports System.Diagnostics

     

    Partial Public Class _Default

        Inherits System.Web.UI.Page

     

        Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

            Dim mStr() As String = {"a", "aaaaa", "aaaaaaaaaa", "aaaaaaaaaaaaaaaaaaaa"}

            Dim mNumberOfConcats() As Integer = {10000, 25000, 50000, 100000}

            Dim mStrBuilder As New StringBuilder()

            For Each mStrElement As String In mStr

                For Each mConcatNumber As Integer In mNumberOfConcats

                    Response.Write("Normal concatenating '" & mStrElement & "' " & mConcatNumber & " times:<br />Operation took: " & _

                                        ConcatNormal(mStrElement, mConcatNumber) & "<br /><br />")

                    Response.Write("StrBuilder concatenating '" & mStrElement & "' " & mConcatNumber & " times:<br />Operation took: " & _

                                        ConcatStringBuilder(mStrElement, mConcatNumber) & "<br /><br />")

                    Response.Write("Array concatenating '" & mStrElement & "' " & mConcatNumber & " times:<br />Operation took: " & _

                                        ArrayConcat(mStrElement, mConcatNumber) & "<br />_______________________________________________<br />")

                    Response.Flush()

                Next

            Next

        End Sub

     

        Private Function ArrayConcat(ByVal pStr As String, ByVal pNumberOfConcats As Integer) As Long

            Dim mStopWatch As New Stopwatch()

            Dim mStr As String

            mStr = ""

            GC.Collect()

            mStopWatch.Start()

            Dim mStrArray(pNumberOfConcats) As String

            For i = 1 To pNumberOfConcats

                mStrArray(i - 1) = pStr

            Next

            Dim mFoo As String

            mFoo = [String].Join("", mStrArray)

            ArrayConcat = mStopWatch.ElapsedMilliseconds

            mStopWatch = Nothing

        End Function

     

        Private Function ConcatNormal(ByVal pStr As String, ByVal pNumberOfConcats As Integer) As Long

            Dim mStopWatch As New Stopwatch()

            Dim mStr As String

            mStr = ""

            GC.Collect()

            mStopWatch.Start()

            For i = 1 To pNumberOfConcats

                mStr += pStr

            Next

            ConcatNormal = mStopWatch.ElapsedMilliseconds

            mStopWatch = Nothing

        End Function

     

        Private Function ConcatStringBuilder(ByVal pStr As String, ByVal pNumberOfConcats As Integer) As Long

            Dim mStopWatch As New Stopwatch()

            Dim mStr As String

            mStr = ""

            GC.Collect()

            mStopWatch.Start()

            Dim mStrBuilder As New StringBuilder()

            For i = 1 To pNumberOfConcats

                mStrBuilder.Append(pStr)

            Next

            mStr = mStrBuilder.ToString()

            ConcatStringBuilder = mStopWatch.ElapsedMilliseconds

            mStopWatch = Nothing

        End Function

    End Class

    Method / Number of concatenations

    10000

    25000

    50000

    100000

    Normal 1 char

    79

    432

    2538

    17336

    StringBuilder 1 char

    0

    0

    1

    3

    Array Join 1 char

    0

    41

    1

    3

    Normal 5 chars

    502

    5664

    24183

    95160

    StringBuilder 5 chars

    0

    1

    2

    4

    Array Join 5 chars

    0

    1

    2

    4

    Normal 10 chars

    1716

    11777

    47859

    209215

    StringBuilder 10 chars

    0

    1

    3

    7

    Array Join 10 chars

    0

    1

    2

    5

    Normal 20 chars

    4395

    24340

    105893

    454174

    StringBuilder 20 chars

    1

    2

    5

    16

    Array Join 20 chars

    2

    1

    3

    7

     

    The results are in milliseconds and clearly shows that the overhead of instansiating the StringBuilder has no measureable performance hit compared to the normal concatenation. Even when making 10000 concatenations on a 20 character string the StringBuilder only uses 1 millisecond!

    What is more interesting is the impact on performance the length of the string that you’re concatenating has on the normal concatenation. Concatenating 1 and 5 characters 10000 times is over 6 times slower and when you compare 1 and 10 characters it is 21 times slower.

    The reason that we even bother thinking about performance is that humans do not like to wait to long, before getting a response to their action. Usually we don’t want to wait more than 2-3 seconds for a response. We must asume that our application must do other things than just the concatenation. That properly means that the concatenation process maximum can take between 500ms and 1000ms. Assuming that we use normal concatenation – how many concatenations can be made within that timespan?

    String length / Runtime

    100ms

    250ms

    500ms

    1000ms

    50

    1252

    1815

    2456

    3419

    100

    482

    1228

    1670

    2413

    200

    565

    866

    1206

    4689

    400

    387

    606

    827

    1178

     

    This again shows that the length of the strings that you’re concatenating is extremely important in regards to the performance.

    To sum up my advice would be to always use the StringBuilder class. It might require 2-3 extra lines of code, but there’s no measureable penalty and you will ensure that your application is extremely scalable. The way I see it there’s no reason not to use the StringBuilder. Better safe, than sorry…always use the StringBuilder people!

    What are your thoughts on the subject?

    Is there any aspects that I’ve missed in my tests?

    Feel free to comment!

     

    In programming we often deal with collections of different classes. It can be a collection of person objects, pupil objects, teacher objects or whatever type of objects you’re handling. A lot of the operations we perform on these collections are very often similar to each other. You can choose to implement a custom collection class to handle each type of objects, but this approach is cumbersome and creates a lot of redundant code. You can also choose to store your objects as the object base class System.Object and the cast the objects to the correct class when you need to. However this approach generates a lot of overhead, when casting objects to and from the different classes and on top of that it also increases the risk of runtime errors considerably, because we sometime try to cast an object to the wrong class.

    Generics provide an elegant and easy solution to this problem. Generics allow us to postpone the declaration of what type a class contains to runtime instead of compile time. Take this simple example:

    class Gen<T>

        {

            public T t1;

            public T t2;

     

            public Gen(T pT1, T pT2)

            {

                this.t1 = pT1;

                this.t2 = pT2;

            }

        }

    class Program

        {

            static void Main(string[] args)

            {

                Gen<string> mGen = new Gen<string>("Hello", "World");

                Gen<int> mGen2 = new Gen<int>(12, 13);

                Console.WriteLine(mGen.t1 + mGen.t2);

                Console.WriteLine(mGen2.t1 + mGen2.t2);

                Console.ReadKey();

            }

        }

    The first declaration is the generic class. Note the angle brackets after the class name. Here the class has the possibility of having 1 type, but it is also possible for a generic class to have more than one type eg. Class Gen<T,U> would yield that the class had 2 different types (not necessarily 2 different types). When we run our small program we create to different instances of our Gen class. One requires strings and the other requires integers. When we use the + operator on the two instances of Gen, it is used accordingly to the type declared in the generic class definition. So the program results in the following result:

    HelloWorld

    25

    Of course this is a very simple example and we soon run into problems if we try to use methods that are not inherited from System.Objects. If we try to call the split function on either t1 or t2, the code will compile for mGen but not for mGen2. This is because int does not have a method called split.

    This problem is solved very elegantly by using constraints. When you apply constraints on a generic class, you place a requirement o the types that the consuming code can substitute for the generic parameter. The 2 most used types of constraints are Interface constraints and Base class constraints. Basically you can set up a constraint that the generic parameter must implement a certain interface or inherit from a given base class.

    An example of this could be if we have a Person interface, which states that the implementing class must have a function called Income. We have 2 classes that implement the interface – Pupil and Teacher. The 2 classes have different implementations of how the income is calculated. If we have a generic class that handles storage which have the constraint that the type of the generic type parameter implements the interface, then the compiler will ensure that no matter what object is returned from the collection, then we can call the Income method on this object.

    In this simple example I declare a small interface and a generic class which has the constraint that the parameter type of the generic class implements the Person interface.

    interface Person

        {

            int Income();

        }

    class PersonCollection<T>

            where T : Person

        {

            private List<T> cCollection;

     

            public PersonCollection ()

            {

                cCollection = new List<T>();

            }

     

            public void Add(T pElement){

                cCollection.Add(pElement);

            }

     

            public T Get(int pIndex)

            {

                return cCollection[pIndex];

            }

        }

    Now we have a collection class that can store all classes that implements the Person interface and that means that we have a guarantee from the compiler, that there is a Income method defined no matter what type is stored in the generic collection class. Observe that I’m using the List<T> class, which is one of the generic collection classes which comes with .NET.

    Pretty neat stuff, huh?

     

    Yesterday I started a preperation course for Microsofts 70-536 exam (application development foundation). It is the first part of Microsoft’s MCTS in ASP.NET, which I plan to finish during 2010. Even though a lot of the curriculum is fairly basic, it is still very interesting stuff. It turns out that there are a lot of things that I didn’t know about the framework and how it fundamentally works. I figured that the stuff that I find interesting might be interesting for others too and therefore I’ve decided to write a few posts about the stuff that we cover in the course.

    This blog post is about some of the inner workings of .NET: the stack and the heap. Most programmers have a fairly good idea about what it is – but what is the actual difference between the two? And how are they used?

    Basically both the heap and the stack are memory that .NET uses for the different variables and objects. The stack is a memory block which only contains variables that have a constant size – also called value types. Int, double and Booleans are all value types, because they all have a fixed size (32 bits, 64 bits and 1 bit byte). Strings are not a value type. This is because a string does not have a predefined length and therefore the stack does not know how much space is required to store the string. String and all other classes are reference types. They are called reference types, because they are characterized by having a reference on the stack to the place on the heap.

    The heap holds all of our objects and is a much more dynamic type of memory than the stack. The main difference between the two is that the stack is much faster than the heap. It is not slower to access objects in the heap than on the stack as such – but the overhead required to maintain the heap. The maintenance of the heap is called garbage collection and is the operation of going through the objects in the heap, removing all the objects that no longer have a reference in the stack and refragmenting the memory.

    A small twist to the types that can be stored on the stack, is that structures also can be stored on the stack - but only if the structure only contains value types. For instance is System.Drawing.Point is a value type. It represents an ordered pair of integer x- and y-coordinates that defines a point in a two dimensional plane. The structure does not contain any reference types and therefore it is also a value type.

     

    As a part of my morning routine I read a lot of news pages on different subjects that interest me. But I also read a lot different techincal blogs. I think that it is a great way to get new input as a developer and supports my own development as a "code monkey". This small post is just link to some of the blogs that I find interesting.

    Janko at warp speed is definitely one of my favorite blogs. Janko has a lot of interesting blog posts about development, design and UI. His posts are always extremly well written, entertaining and very informative.

    Scott Gu's blog is also a great blog to follow. Scott Guthrie is the Corporate Vice President, .NET Developer Platform and blogs about alot of the new stuff that Microsoft is coming up with. Very interesting stuff if you like to follow the newest .NET technology.

    The guys behind the Stack Overflow podcast, Joel Spolsky and Jeff Atwood, both have some great blogs. Especially Jeff Atwood has some great and very entertaining posts. Joel does not post very frequently anymore and stated, in a recent Stack Overflow podcast, that he's planning to stop the blog soon.

    Scott Hanselman's blog is also great fun to follow. His posts are both on development but also about all kind of other nerdy stuff.

    Justin Etheredge has a blog called CodeThinked. His blog posts are very, very well written and is about different kind of development aspects - often about .NET.

    Dave Ward's blog, Encosia, is also a very interesting blog. Unfortunatly Dave Ward doesn't post very often - usually only once or twice per month.

    I also subscribe to some news aggregating feeds:

    DZone

    DotNetShoutout

    Smashing Magazine

    ASP.NET Daily Articles

    Go check some of these blogs and feeds out. I hope you enjoy them as much as I do.

    So far I've only posted a single post on this blog, which was the introduction to why I've started this blog...and I was way back in August. Very embarrasing! But now I've decided to get started. This small post is the solution to a very small but common task in webdevelopment: Dynamically generate the options in dropdown

    Say you've a select in your page like this:

    <select runat="server" id="ExpireYear" name="ExpireYear">
    </select>

    The contents of the select differs from time to time the page is loaded. I had a page which held a select box with the next 10 years in and of course I don't want the values of the option elements hardcoded in the code. Therefore I made a small Sub in my code behind which fills out the select box with option elements:

    Private Sub GetYearOptions()
    Dim mCurrentYear As Integer
    Dim mShortYear As Integer
    Dim i As Integer
    Dim mListItem As UI.WebControls.ListItem
    mCurrentYear = DatePart("yyyy", Now)
    mShortYear = mCurrentYear - 2000 'I want 10 instead of 2010
    For i = mShortYear To mShortYear + 9
    mListItem = New UI.WebControls.ListItem(i, i)
    ExpireYear.Items.Add(mListItem)
    Next
    End Sub

    ExpireYear is the id of the select box and options are easily added by using ExpireYear.Items.Add(pListItem). The two parameters to the ListItem constructor is the text of the element and the value of the element.

    I realize that this is a very trivial little post, but everyone has to start somewhere and hopefully this will be the start of better and better blog posts from me.

    kick it on DotNetKicks.com

    Zteff , 1. August 2009, 00:33

    The purpose of this blog is to document some of the subjects and solutions to different programming problems that I find interesting. Hopefully some of the blog posts will help and inspire other fellow programmers. My main interests are the .NET framework, with main focus on ASP.NET, C# and VB.NET, jQuery and UI, but I also find SQL, VbScript and agile development interesting.

    I’m a fairly young programmer living and working in Copenhagen, Denmark. I've only worked as a developer since I finished my bachelor degree in computer science from Copenhagen University in 2007. I quickly found out that the very theoretical approach to computer science that I had from the university was not of much use when I started my professional career. Therefore I decided that I would dedicate myself to becoming the best developer I could possibly be. As a part of this process I started to read a lot of programming blogs, read books on the subject and participate in the programming community in general.

    This blog is the next step for me in the process of becoming a better programmer. Here I will post my thoughts, problems and hopefully some solutions to these problems. I must stress that I am not a programming guru and therefore my posts are not guaranteed to be perfect let alone flawless. But I hope that if you find an error in a post or have a better solution, you will post a comment with your thoughts.

    Thanks for dropping by!

    Regards,

    Steffen