Keep it simple (and help to save the planet)

Today I came across a piece of code like the following.

Dim strSQL As New StringBuilder
strSQL.Append("SELECT ")
strSQL.Append(" ProductID, ")
strSQL.Append(" Name ")
strSQL.Append("FROM Production.Product")

Try
    cnnConn.Open()
    Dim cmd As New SqlCommand(strSQL.ToString, cnnConn)

When I encounter code I don’t agree with, I try to understand what made the developer code it that way.

Looking at this one I can only presume:

  1. He wanted to make his code more legible by separating the SQL Command to different lines.
  2. In doing that, he wanted to avoid string concatenation, because "string concatenation is performance wise evil"!

My answers to these points are:

  1. In this particular case, the code became harder to read than if it was stated in a single line.

    Dim strSQL As String = "SELECT ProductID, Name FROM Production.Product"

  2. That may be true in a lot of situations, but is not true in this particular one: concatenating small string constants, as the compiler is smart enough to generate one single string constant comprised of what we see in code as being multiple strings being concatenated

    Dim strSQL As String = _
    "SELECT " + _
        " ProductID, " + _
        " Name " + _
        "FROM Production.Product"

    Try
        cnnConn.Open()
        Dim cmd As New SqlCommand(strSQL, cnnConn)

    gets compiled to

    L_001f: ldstr "SELECT  ProductID,  Name FROM Production.Product"
    L_0024: stloc.1
    L_0025: nop
    L_0026: ldloc.2
    L_0027: callvirt instance void [System.Data]System.Data.SqlClient.SqlConnection::Open()
    L_002c: nop
    L_002d: ldloc.1
    L_002e: ldloc.2
    L_002f: newobj instance void [System.Data]System.Data.SqlClient.SqlCommand::.ctor(string, class [System.Data]System.Data.SqlClient.SqlConnection)

 

* Q: So what does this post has to do with saving the planet?

A: Keep it simple -> spend less processor cycles -> spend less energy -> … -> … ->…. Oooh… you get it!

Advertisements
This entry was posted in Visual Basic. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s