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!

Published by

Alfred Myers

I have been interested in computers since I got my hands on a magazine about digital electronics back in 1983 and programming them has been paying the bills since 1991. Having focused on Microsoft-centric technology stacks for the best part of two decades, in recent years I’ve been educating myself on open source technologies such as Linux, networking and the open web platform.

One thought on “Keep it simple (and help to save the planet)”

Comments are closed.