C# String Performance

In my last post, I talked a bit about JavaScript performance specifically around For loops. Today’s topic is also performance related but specifically around building strings in C# in loops.

I think every programmer has had occasion to build quite large strings at runtime. Typically, however, string operations can cost you a lot in performance. I had run into this issue recently. I had started out building a large string with just simple concatenation like so:

string MyString = string.Empty;

for (int i = 0; i < 1000; i++)
    MyString += " This is an addition to MyString " + (i + 500).ToString() + " Some more addition to MyString";

We’ve all seen and used an approach similar to this. It’s easy to read and understand (generally). However, this little sample is really inefficient. It took 237 milliseconds on my machine. Hmm, maybe not so good.

Let’s try another way:

StringBuilder MyStringBuilder = new StringBuilder();

for (int i = 0; i < 1000; i++)
    MyStringBuilder.Append(" This is an addition to MyString " + (i + 500).ToString() + " Some more addition to MyString");

This approach only took 1.9 milliseconds! That’s a huge difference if you’re trying to shave your page load time down.

So what if we increase the upper bounds to say 10,000?

String Concatenation: 24,371 Milliseconds (24 Seconds)
String Builder: 29 Milliseconds (0.029 Seconds)

Now that’s a huge difference! You’d better believe that would make a difference in response time!

The big reason for the difference is that the string is being build in a loop. If you had a one-off string to build, you may not see that big of a difference. But if you using a loop, you’ll be much better off using String Builder!



JavaScript For Loop Performance

A while back I wrote about creating HTML tables for tabular data and then using the jQuery plugin jEditable to allow inline editing of that table. The approach works well over all but there’s two areas where it falls apart – when the table has a large number of rows and when using older browsers (especially IE).

My first take on writing a framework to render the HTML table was in JavaScript. I liked it because everything was in JavaScript except the data access layer. However, when the table has a large number of rows, rendering it in the browser doesn’t work well – especially when your most commonly used browser is IE 8.

While IE 8 is an improvement over IE 6 & 7, it is still pitifully slow in executing JavaScript. I learned this after the fact, when I can a complete framework. It wasn’t too apparent with just one or two grids on the page, but when I had five grids and each at least several rows, IE 8’s slowness became painfully apparent. So, off to do a deep dive into JavaScript performance in IE 8.

My  approach had been to make an AJAX call, retrieve a DataTable that was converted to JSON and then loop through that on the client, gradually building out the HTML table. One of the first performance issues I found was the wide variety of JavaScript loops and their various speeds. It turns out that while IE 8 is very slow over all, there are several JavaScript loops that are really slow.

Here are two different benchmarks for JavaScript For Loops:

Check them out; I’ll wait.

Notice the graphs for IE 6, 7, or 8? They barely even register on the overall graph. If you are interested in specific loop performance, you can run the test and see the operations per second number.

What I found was that in IE 8, for…in loops only where clocking in at around 150 ops/sec. While modern Chrome and Firefox were in the thousands. This was a bit frustrating because the for…in loops made it really easy to work with the JSON that was being return to the client. Foreach loops and jQuery loops were also quite bad.

So my rule of thumb going forward, is to use just a plain, native for loops. At least in the older IE browsers, they represented the fastest possible execution times.




Latest Project – The Man Sale

For the past two weeks or so, I’ve been working on a website for a side-business that my wife and I are starting up. This project was a little different than any WordPress project I’d attempted before. We had found a HTML template that we really liked. Being that designing logos and colors from scratch is not my strong suite, we decided to purchase it. I then converted it to a really basic WordPress theme that could be applied from the Dashboard. I’m please with how the conversion turned out.

Home Page

(click for a larger image) Home Page

Secondary Page

(click for a larger image)


You can check out the full website at If you’re in the area, consider consigning items or shopping at the sale in December!

If you have a HTML/CSS/JavaScript layout or design that you would like to apply to your WordPress site, give me a shout! I offer packages for basic WordPress website setup and layout starting at $500.



Using Perfmon Counters to Gather Performance Data

You’ve probably heard the saying that knowledge is power. Indeed it’s very hard to make good decisions about complex problems without data. Data gives you the insight to know what’s going on so that you can make quality decisions that will actually help solve the problem.

Recently, I’ve been dealing with some performance issues in a Sql Server 2008 R2 database. Microsoft has built counters into Windows, Sql Server and ASP.NET that allow you to gather metrics about specific operations. Many of these counters have industry standard thresholds that you can compare your actual numbers with to help identify when there is a problem.

So how do you get this data? If you know C# or VB.Net, it’s super easy. Here’s a simple, rough example:

class Perfmon
   private static PerformanceCounter _percentProcessorTime
     = new PerformanceCounter("Processor", "% Processor Time", "_Total");

   static void Main(string[] args)
       if (PerformanceCounterCategory.CounterExists("% Processor Time", "Processor"))
           var actual_percentProcessorTime = _percentProcessorTime.NextValue();
           //Do what you want with the counter data.

Pretty easy, right? But how do you know which performance counters to gather data from? Fortunately, there are a number of good resources out on the interwebs. One of the best resources I’ve found for gathering Sql Server specific performance data is a poster from Quest (now part of Dell; makers of TOAD software). You can download the poster here (PDF). This poster gives a number of Perfmon counters that deal with the physical server and Sql Server. As it lists each counter, it provides a description and a threshold, if applicable. The thresholds are really helpful when starting to gather this data and make sense of it.

You can also gather counter data via the Perfmon.exe application that comes baked into Windows. This tool allows you to log the data to a number of file formats (CSV, Binary) and also log directly to a Sql Server table if you wish). Check out this article and video from Brent Ozar for more information there. The Perfmon tool will also graph the data in real time, much like the Windows Task Manager does.

A third option is available if you wish to only gather Sql Server metrics (including things like recent expensive queries). This link, gives you the actual queries that you can run (providing you have login credentials with the appropriate rights). You could even leverage SSRS (Sql Server Reporting Server) to build a report against the data and create a real-time dashboard.

I opted to retrieve the counter data from a C# console applications for two reasons: first, C# is what I’m the most comfortable with. But secondly, I wanted to be able to insert checks based on the recommended thresholds and provide real-time alerts via email to the team.

If you wish to log the data via the Perfmon.exe tool and then analyze the data after the fact, I recommend that you check out the Performance Analysis of Logs (PAL) tool. It’s free! It provides you with a number of threshold files that you can use to compare the gathered data against. You can export the threshold files to import them into the Perfmon.exe application so you don’t have to manually set up all of the recommended counters. PAL will built a list of times where thresholds were exceeded or were close to being exceeded. But that’s not all, it will plot the data on graphs. I highly recommend this tool!

Happy Data Crunching!



Loyalty and Layoffs

I just finished listening to the latest Ruby Rogues podcast and really enjoyed it. It covers the dynamics between the employee and employer and how they’ve changed over the years. I really enjoyed it and think that you should have a listen.

125 RR Loyalty and Layoffs.



Simple JavaScript Hooks

I recently had cause to inject some business logic into a JavaScript framework. I’m trying to keep the framework as generic as possible so I want to keep from hard-coding the business logic directly into the framework. In a C# context we might simply override the desired method to insert our behavior. You can override a function, in a way, in JavaScript. However, in my opinion, it’s not as clean.

After doing a bit of research, I found the following approach using jQuery. So far it works well. You define your ‘hook’ by simply doing the following:

 $(document).bind('OnSave', function() {
    //Insert code/logic here.

To execute the hook, you simply do this:


The beauty of this approach is that if you don’t bind a hook called ‘OnSave’, nothing happens. You are free to bind a function to the hook or not. It’s your choice.

You can also pass parameters into the hook like this:

 $(document).trigger('OnSave', [description, value]);

Where ‘description’ and ‘value’ are arbitrary variables that you want to pass to the hook. When using these hooks, the bind method call looks like this:

 $(document).bind('OnSave', function (description, value) {
     //Insert code/logic here.

That’s it! You can find the jQuery documentation for here and here.

Happy Coding!



WordPress Event Calendars

Recently, I was working on the website for the church I attend (Mercersburg Church of God). We had some upcoming events that we wanted to get the word out to the community.

My first thought was to have a page with a calendar layout and just list each event on the day it occurred. My personal preference is to use an existing product, if it’s available, rather than always writing each feature need from scratch. So I went looking in the WordPress plugin site.

There are a number event calendar plugins out there but I settled for one from Modern Tribes; aptly named ‘The Events Calendar’. The basic version is free but there is a pro version that costs but gives you several extra benefits, including support.

I’ve been very impressed with this plugin. It gives you the month at a glance view but it also has a list view. It will list each event under the month heading and the event description. But if the viewer would like more information, you can drill down into the event for more details.

The detail view contains contact information, the event description and, if you provide the event’s address, it will plot the event on Google Maps.

I really liked the plugin because it made my job as a site admin super easy. If you need this functionality for your site, I would highly recommend it!



JavaScript Data Grids

I recently had cause to build an editable grid out of HTML and JavaScript and settled on two jQuery plugins: DataTables and jEditable. I’ve really been impressed with both!

The DataTables plugin takes a basic HTML table and adds column sorting, filtering, pagination and much more. To create the default grid all it takes is the following:


The jEditable plugin allows the grid contents to be edited inline. So all you have to do is click on a value and a textbox or select list appears. Like DataTables, jEditable is quite flexible. Basic initialization is as easy as:


What I love about the jEditable plugin is that if you want a select list to appear when the cell is in edit mode, all you have to do is this:

  $('.editable').editable('http://URL_To_Page_To_Handle_Database_Action', {
    type: 'select',
    data: {’Ford’:‘Ford Motor Company’,‘Honda’:‘Honda North America’,‘selected’:'Toyota'} 

This configuration will cause the field to be a select list in edit mode and populated with the car company information in the data array. If you need the select list to be dynamically populated, you can provide jEditable with an array of values.

Since you initialize jEditable using a jQuery CSS selector, you can choose which columns become editable or even which columns are textboxes and which are select lists while in edit mode. Just apply unique CSS classes to the correct column.

If you use ASP.NET, you can create a method on page and decorate it with the [Web_Method] attribute. Then you can use the jQuery AJAX method to send data changes to an update method to be written to the database. If you want to have your select list be dyanmic (as mentioned above) you can also use the jQuery AJAX method to retrieve your option list.

If you didn’t need the pagination, sorting, filtering or other features provided by the DataTables plugin, you can just use the jEditable plugin on the HTML table.

I used these two plugins to replace ASP.NET grid views. The page had grown over time to be quite complex with a number of grid view controls on the page. The grids had become slow and the View State was very large. These plugins allowed us to give the end user an editable grid but with great performance and much less overhead.



Let’s Go!

Hi! If you’ve been around here before, you’ll probably notice it looks different. I’ve converted this site to be the home of my new freelancing business.

Starting today, I have availability for projects. I can build you a website in ASP.Net or WordPress. I’ve been a professional ASP.NET developer for over five years and bring considerable experience to the table. I’ve recently started working with WordPress but don’t let that fool you! I’ve really come to enjoy the platform.

Do you need a blog with a custom domain name? Do you need a website for your small business? Can do! Do you need a web application to collect data, stream line a process or to support a new branch of your business? Can do! What about voice services or text messaging from your application? I can use Twilio to easily integrate both features into your applications.

Contact me today! I look forward to hearing from you!