An interesting test came up recently where we needed to URL encode everything but the slashes in an URL.  What is the best way to handle this speed wise as well as memory wise.

 

Method 1: Split/Join.  Split the URL by ‘/’, loop through and UrlEncode the pieces then Join it back together with ‘/’

Method 2: Replace. Url encode then replace ‘%2f’ with ‘/’

Method 3: Split/Concat. Split the URL by ‘/’, loop through the and UrlEncode the pieces then concatenate them to a final string

Method 4: Split/StringBuilder.  Same as Method 3 but use a StringBuilder with append instead of +=.

 

I wanted to know the difference in memory usage as well as speed between the methods.  There are situations where memory overhead is more important than speed like when running code on a large, heavily used, internet web site hosting tens to hundreds of applications per server.  Well the only way to prove is to test it so we brought out the trusty profiler and created the four tests.

 

Each test ran 1 million loops.  The URL was the same on each loop

 

Test

CPU Clock cycles

Memory page footprint of code

Memory page footprint of

Split/Join

25,196,702,658

11

1428

Replace

16,696,889,076

14

1424

Split/Concat

28,150,537,966

17

1422

Split/StringBuilder

28,492,659,174

25

1433

 

Notice that the test with StringBuilder actually took more clock cycles and more memory than all the rest.  Odd, at least I know that Replace kicks but now I’m wondering about efficiencies built into .NET when the URL is the same.  I’m going to need to test this again with a variable URL.

 

This posting is provided "AS IS" with no warranties, and confers no rights.