Wednesday, November 12, 2008

String Vs. StringBuilder classes

One of the .Net performance efficiency tip that we, developers keep hearing from all quarters is to use StringBuilder over String concatenates.

Now, lets see what actually happens behind the scenes. Are people right when they StringBuilder is better? Does it have a performance edge? If so, when?

Scenario 1:
String Concatenation
String sStringHolder = "";
Random rRandomize = new Random(150);

DateTime dtStartTime = System.DateTime.Now;
for (int iCount = 0; iCount < 10000; iCount++)
{
sStringHolder = sStringHolder + "1";
}//for(int iCount=0; iCount<1000; iCount++)
DateTime dtEndTime = System.DateTime.Now;

Trace.WriteLine("Time taken using the Concat operation >> 10000 Iterations: ");
Trace.WriteLine(((TimeSpan)(dtEndTime - dtStartTime)).Milliseconds);

dtStartTime = System.DateTime.Now;
for (int iCount = 0; iCount < 20000; iCount++)
{
sStringHolder = sStringHolder + "1";
}//for(int iCount=0; iCount<1000; iCount++)
dtEndTime = System.DateTime.Now;

Trace.WriteLine("Time taken using the Concat operation >> 20000 iterations: ");
Trace.WriteLine(((TimeSpan)(dtEndTime - dtStartTime)).Milliseconds);
The first iteration (for 10000 loops) took 46 milliseconds while the second iteration where the loop count doubled (20000 loops) increased almost 9 times (375 milliseconds).

So, what does really go on inside? Why are the results so drastically different?
sStringHolder = sStringHolder + "1";
Strings are immutable, i.e., the value can not modified once it is created. So, in this case three instance of the String objects are created to accommodate the concatenation. When a concat is performed, the old sStringHolder is discarded and a new one created to hold the newly concatenated string. That is the reason why it becomes too expensive.

Scenario 2
StringBuilder Goodness
StringBuilder sbStringHolder = new StringBuilder(50);

dtStartTime = System.DateTime.Now;
for (int iCount = 0; iCount < 50000; iCount++)
{
sbStringHolder.AppendFormat("{0}", "Hello");
}//for(int iCount=0; iCount < 1000; iCount++)
dtEndTime = System.DateTime.Now;

Trace.WriteLine("Time taken using StringBuilder class:AppendFormat >> 50000 iterations: ");
Trace.WriteLine(((TimeSpan)(dtEndTime - dtStartTime)).Milliseconds);
That was 15 milliseconds for a 50000 count iteration! StringBuilder certainly has an edge here.


This advantage that StringBuilder has is due to the fact that the string allocation and copies does not have to be as frequent as a String Concatenate. That's from where the majority of the savings come from. But if the StringBuilder has a buffer that's just right for the string that it holds, it will have to grow on every Append which is as good (or bad) as the string concatenate.

Although, this cannot be taken as a rule of thumb that StringBuilder is always more efficient than a String concatenation - Rico Mariani explains the four different cases.

Big string and small appends
=>It's substantially likely that appends will fit in the slop and so they're fast, this is the best case(buffer size becomes double the string when it no longer fits so on average the slop is half the current string length) (if there are lots of small appends to a big string you win the most using stringbuilder)

Big string and big appends:
=>While the string is comparable in size (or smaller) to the appends stringbuilder won't save you much, if this continues to the point where the appends are small compared to the accumlated string you're in the good case

Small string big appends:
=> bad case, string builder will just slow you down until enough slop has built up to hold those appends, you move to "big string big appends" as you append and finally to "big string small appends" if/when the buffer becomes collossal

Small string, small appends:
=> could be ok if you had a good idea how big your string was going to get and pre-allocated enough so that you have sufficient slop for the appends. You might be able to do better if you just concatenated all the small appends together in one operation.

Otherwise put, if the operation that is to be performed is something like this:
x = f(x) + f(y) + f(z) + f(a) - String Concat is better

If the operation will be something to this effect:
x += f(x);
x += f(y);
x += f(z);
x += f(a) - StringBuilder will suit better in this scenario

Thursday, November 6, 2008

The ?? Operator

Today was my first brush with the ?? operator and was pleasantly surprised by what it can do.


string sString1 = null;
string sString2 = "Hi";
string value = "";

// We would normally it this way
value = sString1 != null ? sString1 : sString2;

// Using ?? operator also called as coalescing
value = sString1 ?? sString2;

// In effect, it could be string
// val = a ?? b ?? c
// - The first non-null value is assigned to val
Response.Write(value);


Chaining ?? operator certainly makes it easier to perform a bunch of comparisons. When the ?? operator is chained, it assigns the value of the first non-null value.

Friday, October 24, 2008

Hourglass (Wait) cursor on page load

This is another pearl that was figured at work today. There are instances where we might want to turn the cursor into a hourglass symbolizing that the user needs to wait as the page is getting loaded. There are more than one way to achieve this. There are two that comes to my mind (please feel free to add more)

1. Using AJAX - UpdateProgress Extender that displays a wait modal popup extender when the page is getting loaded and ready
2. A simpler approach is to use JavaScript that does exactly this

We are going to see the second approach at work -
function doWait()
{
document.body.style.cursor = 'wait';
}
<
body onbeforeunload="doWait();" onunload="doWait();">
Notice the events onbeforeunload() and onunload() events. The reason we use two events is that these events are browser dependent and so to behave well with different browsers, we do this!

Both Mozilla FireFox and Internet Explorer implements onbeforeunload() DOM events.

Another useful function of onbeforeunload() is to alert the user when he leaves the webpage. Read here to know more about this DOM event.



Tuesday, October 14, 2008

Capitializing first letter of every word

The ToTitleCase method in .NET is not a part of String class but of TextInfo class that resides in System.Globalization namespace. This method converts the first character of every word into upper case. Here's how to use it,

String sHelpText = "aN eXamPle tEXT";
System.Globalization.CultureInfo oCInfo = System.Threading.Thread.CurrentThread.CurrentCulture;
System.Globalization.TextInfo oTextInfo = oCInfo.TextInfo;

return(oTextInfo.ToTitleCase(sHelpText.ToLower()));

Note: The .ToLower() Method is used to explicitly convert the string into lower case. According to MSDN - the title casing converts the first character into upper case, except for a word that is upper case in entirety. Read more on this here.


Friday, October 10, 2008

Faster Firefox 3.0

While you were thinking about giving up FireFox due to its speed and memory bloats, Mozilla came out with 3.0 - a relatively faster successor.

Now, is it possible to tweak FireFox 3.0's default settings and make it work at lightening speed? Here are some of FF 3.0 browser tweaks.

For the uninitiated - you don't want to see all the gruesome details of application settings, but still want to experience the speed? Rush ahead to https://addons.mozilla.org/en-US/firefox/addon/9148, install the add-on. From my experience, there is a consistent 30-40% increase in the browser's rendering speed for the web pages. Go on! Try it.

For those of you, who would like to know the nuts and bolts of everything - read on!

HTTP is the application-layer protocol that web pages are transferred with. In HTTP 1.1, multiple requests can be sent before any responses are received. This is known as pipelining. Pipelining reduces page loading times.

1. Open FireFox
2. Type about:config in the address bar and press Enter
3. In the filter bar type network.http.pipelining. Double-click to set it to true
4. Return to the filter bar and type network.http.pipelining.maxrequests. Double-click this option and set its value to 8.
5. Go to the filter bar and type network.http.proxy.pipelining. Once it opens double-click it to set it to true.
6. Right-click Preference Name and create a new Integer value. Enter content.notify.backoffcount in the New integer value pop-up window and click OK.
7. Right-click Preference Name and create a new Boolean value. Enter plugin.expose_full_path in the New boolean value pop-up window and click OK.
8. Right-click Preference Name and create a new Integer value. Enter ui.submenuDelay in the New integer value pop-up window and click OK.

These all the common settings for everyone. Check out below for specifics:


Note: A faster computer means - >513 MB Memory and 1.5 Ghz and a Faster Connection means - DSL/Cable (not dialup)

Thursday, September 25, 2008

Forgotten Attachment Detector

For those few that are not aware of GMail Labs yet - GMail Labs is an experimental ground for trying out the new ideas and features from the Google team. These add-ons may or may not make it to the GMail feature list in future. Meanwhile, it is certainly worthwhile to try our hand at them.

I was awed and pleasantly surprised by this new GMail Labs feature available. Forgotten Attachment Detector warns you about sending an email without attachments. According to Jonathan K, the author of this wonderful piece of code from Google Labs - Forgotten Attachment Detector prompts you if you mention attaching a file, but forgot to do so.

See the prompting feature in action!


This is such a cool feature that it makes me think - how did we miss having this all along on an email client. Kudos to Jonathan and the team at Google labs! This add-on looks for the the word 'attach' or its derivatives in the email before sending it (somehow, it thinks 'attachments' is not one of those and does not prompt for the files to be attachments!!)

If you have still not enabled this Labs feature, take a look at how to enable them


And then enable the Forgotten Attachment Detector - and voila, you are all set!



Tuesday, September 23, 2008

Modal Popup Extender and flicker issues

ModalPopup extender is a very convenient and easy tool for designing lightbox style modal popups.

During development, I realized that the contents that go in the modal popup box appear for a split second when the page gets loaded. In repeated tries, I was actually able to grab a screen shot of the strange behaviour.

Look at the contents below the button! They are a part of the modal popup contents. Pretty weird, huh?

To get around this - simply set the popup panel's style to display:none.


And the modal popup extender code


Monday, September 22, 2008

Android - Google's 'Dream'

Android - another addition to the U.S smart phone industry. The smart phone market boils to two key players - Apple iPhone and it's competitor RIM Blackberry. The irony, however is that nobody even mentions Windows SmartPhones in that list (that has been in the market for quite a while).

Android OS dubbed GPhone, is about to be launched on September 23, 2008 integrated into T-Mobile's HTC phone, and is called 'Dream'. This would definitely spark a fierce competition between Dream and iPhone during the Christmas period.

Built on the Linux kernel, Android is a so-called open platform where nobody is charged for using it on the phone or for building applications on the phone. Though iPhone has a similar set up for its users and developers where millions of iPhone applications have been downloaded - the catch is that, all applications will have to be available only through iTunes store.

The highlights of Android is guessed to be
  1. Mobile OS-Linux that will include a in-built browser, 2D and 3D graphics, SQLite DB, video and audio playback, GSM, Bluetooth, WiFi, 3G wireless, camera, compass, GPS - that's a standard, neat list
  2. QWERTY keyboard based touch screen with haptic feedback (You can feel the bumps of keys and virtual games)
  3. A complete Java based development environment with a plug-in to Eclipse.
  4. Core applications built with OS - GMail, GDocs, Maps
  5. The price tag is guessed to be around $199 to position itself with iPhone, and to be a direct compeititor. There are rumors that it would be $150 for a existing customer account upgrade.

For an Android walk-through, click here and more screenshots here

As always, an average customer knows what he wants to do with a phone: make and receive calls, send and receive text messages and access some basic online information. However, a couple of months into using iPhone, I can see the excessive dependence on information on the go - Maps, search for business in a locality, emails, messengers and increased productivity.

This launch will be closely watched by a users and developers alike. Unlike iPhone, the impact this launch will cause will not be effectively gauged right after the release - it will take sometime to sink into the minds of people as yet another smart phone. This phone will certainly make its impact on the cost of the mobile and its applications.

Tuesday, September 9, 2008

Google's Chrome

The first thing that catches the eye in Google Chrome is its minimalist design that gives the feeling of a light weight application. Chrome is built on the existing rendering engine Webkit - framework version of the engine used by Safari and Android.

One thing that I find very interesting is the multi-process design of the application. The application resources are not shared between different tabs and so you will be able to isolate that particular website that eats memory. (Yikes! Now you can tell Youtube.com eats about 280MB of the 300MB browser load - Now that's something, isn't?)

Omnibox
The address bar has in-built auto-suggest feature that helps users to get where they are going. Chrome uses Google Suggest to fetch the suggestions as the user starts to type. It allows access to bookmarks, history, search and much more from the same place. This feature is very similar to the one available in Firefox 3.0

Downloads
Downloading has become much more neat and non-intrusive - no more status bars or pop-up dialogues. This features is again very much similar to the the add-ons available for FF, the difference here is that it is built right into the browser.
Performance
The faster the website is rendered, better is the user experience and thus, better is the performance. Chrome takes advantage from its all new Javascript Engine V8 built from scratch by its Denmark team.

Chrome for Developers

DOM Inspector
The HTML Document Object Model can be viewed in a neatly organized tree structure. This however, is not entirely new to the browser world - FF has it. Although, what's new is the CSS style description on the right.


Chrome Inspector derives a lot of inspiration from FF's Firebug (a FF addon, available for IE also) . Chrome Inspector also has the pictorial resources view of the resources and their load time. This DOM Inspector is certainly a welcome start to inspect/edit the live DOM of any web document or XUL application.


JavaScript Console

Another feature straight out of Firebug is JS Console. To view this console, right-click on the webpage > Inspect Element; then click Show console at the bottom tag of the window.

Chrome finally eases JS debugging by providing us with the much awaited auto-complete feature. This command line tool feature will be more handy when used with 'Breakpoint' debugging - something that is available in Firebug and missing in Chrome.


JS Debugger

Chrome equips us with a command-line JS debugger. I looked around Google Chrome's FAQ for developers and could not find more information on how to use this. I am certain that some developers will surely find this tool powerful, but I am not in that league yet.

Memory Usage
Chrome has surely taken us by storm with this feature - a by-product of their multi-process architecture. Click Developers on the Control the current page icon > Task Manager > Stats for nerds - provides a prolific view of the open tabs and the memory usage. Keep hitting F5 - Refresh to corner out webpages that are leaking memory. This information will certainly be useful for developers to identify memory leaks.



Easter Eggs!
Easter Eggs are hidden, intentional messages in a software or application. They are the most interesting finds when an application gets released! I think many of you would agree with me on this! Here are some of the Easter Eggs I found while looking around

Try these at the Google Chrome's address bar and enjoy!
about:internets
about:stats
about:memory
about:plugins
about:histograms
about:cache
about:dns
about:crash