For Loop Using UInt16 MaxValue

A demonstration of a For Loop Using UInt16 MaxValue. How would you iterate through all of the values in an unsigned 16-bit integer?

The following two loops will not work:


for (UInt16 i = 0; i < UInt16.MaxValue; i++)
{
    // Do something
}

for (UInt16 i = 0; i <= UInt16.MaxValue; i++)
{
    // Do something
}

The first loop skips the last value; the second loop goes into an infinite loop when it rolls over.

Let’s take a look at the first loop.


for (UInt16 i = 0; i < UInt16.MaxValue; i++)
{
    // Do something
}

First we need to know what UInt16.MaxValue equates to as a value.  UInt16.MaxValue is hexadecimal 0xFFFF which is a constant value of 65535.  So when we are looking into the loop with for (UInt16 i = 0; i < UInt16.MaxValue; i++) the last iteration will not happen because we would need an overflow value of 65536.  However, since UInt16.MaxValue is a constant value of 65535, the last value causes the loop to exit before the last Do Something is completed.

Let’s take a look at the second loop.

for (UInt16 i = 0; i <= UInt16.MaxValue; i++)
{
    // Do something
}

The problem we are seeing here is an infinite loop gets created.  This again takes us to needing to understand how UInt16.MaxValue works.  As we said, UInt16.MaxValue is the hexadecimal value of 0xFFFF.  So if you look at this loop if will actually go through and complete the last iteration at 65535.  However, in terms of this hexadecimal value, when you add 1 to it after the last iteration if wraps around to 0 again. Hence, our infinite loop problem.

Solution? Use a do/while loop.

ushort i = 0;
do
{
    // do something
}
 while(i++ < UInt16.MaxValue);

This is close to the first loop in our question, but it will cause the Do Something to iterate all the way through before it does a check on the UInt16 value.

Here it is as a test console app to confirm all the above from Guy Ellis.


static void Main(string[] args){
    UInt16 i = 0;
    do    {        if (i == UInt16.MinValue)
        {
            Console.WriteLine("MinValue");
        }
        if (i == UInt16.MaxValue)
        {
            Console.WriteLine("MaxValue");
        }
    } while (i++ < UInt16.MaxValue);
    Console.WriteLine("Enter to finish...");
    Console.ReadLine();}


Multithreading with Parameters

I ran into a task the other day to make my service calls run asynchronously for performance reasons and solved this by Multithreading with Parameters.  When the front of site gets pounded, the logging service will be making too many inline calls causing performance problems. So I had to do some minor tweaking which really was only implementing to new methods.

So basically we had a call right into our service.

_service.LogServiceCall(string log, string info, long number);

First change we make is call a new method to spin off new threads and we will need to create a new object to store the parameters in.

_service.LogServiceCallInParallel(string log, string info, long number); //New Method Call

public class LogginParams
{
    public string Log { get; set; }
    public string Info { get; set; }
    public long Number { get; set; }
}

When creating a thread with parameters you have to pass in an object with parameters. So we will create LoggingParams object, start the thread, then split the parameters back out.  Let’s take a look at the thread starting.

public void LogServiceCallInParallel (string log, string info, long number)
{
    //Create object
    LogginParams logParams = new LogginParams
    {
        Log = log,
        Info = info,
        Number = number
    };

    //Create new thread.
    Thread logThread = new Thread(LogServiceCall);

    //Start new thread
    logThread.Start(logParams);
}

Now all we have to do is call an overloaded method of our original method so that it will work as designed just now with multithreading.

private void LogServiceCall(object parameterObject)
{
    LogginParams pLoggingParams = (LogginParams)parameterObject;
    LogServiceCall(pLoggingParams.Log, pLoggingParams.Info, pLoggingParams.Number);
}

So as you can see here, all we are doing is breaking back out the object and then calling our original method that was being used.


String versus StringBuilder

String versus StringBuilder and what some of the pros and cons are to each. To start off we need to understand what immutable means and what mutable means.  Immutable in basic terms means the original object cannot be altered.  An attempt to alter or concatenate to an existing object will result in a new object being created each time.  A mutable object means that you can add to the existing object without a new one being created.

A String is an immutable object.  So every time that we change a string, a new string is actually getting created.  This is not the most efficient use of memory if you are doing multiple concatenations to a string, you will be creating a new string object each time. This whole discussion of immutability is a deep subject for another post.

So let’s take a look at this loop for if you have a 100,000 iterations of adding a sentence to a string. This is just adding a sentence to the string each time, however because its an immutable object it is creating a new string object each time.  This has memory efficiency issues as well as it can slow down performance when you get large strings and many iterations of adding them together.

private static string LoopResult(string result)
{
    for (int i = 0; i < 10000; i++)
    {
        result += "Lets just concat a sentence on the end of it each time.";
    }
    return result;
}

So what I did was created a simple test method using a Stopwatch and benchmarked 5 runs of this method as follows.

public void IterationTest()
{
    string result = "";

    Stopwatch sw = new Stopwatch();
    sw.Start();
    result = LoopResultConcat(result);
    sw.Stop();

    long elapsedTicks = sw.ElapsedTicks;
}

After 5 test runs these were the outcomes in Ticks.

Using string +=
Test 1 = 20234811
Test 2 = 19659463
Test 3 = 20091368
Test 4 = 19763153
Test 5 = 19698219

Going through the test it didn’t seem to bad considering how many characters and iterations were being taken into account.  However, lets switch it up and use a StringBuilder and do a .append() on the end string during the loop. That looks like this.

private string LoopResult(string result, StringBuilder sb)
{
    for (int i = 0; i < 10000; i++)
    {
        sb.Append("Lets just concat a sentence on the end of it each time.");
    }
    return sb.ToString();
}

This proved to have a substantial gain over the string += method. The results listed below show that using the .Append() method substantially increases the processing time of building the extremely long string.

Using StringBuilder.Append()
Test 1 = 11198
Test 2 = 15684
Test 3 = 12751
Test 4 = 12646
Test 5 = 11763

As a side note, in our main IterationTest() method we will instantiate our new StringBuilder object with a designated capacity.  The StringBuilder object gets allocated a specific capacity, 16 characters when its instantiated; then it gets re-allocated each time it reaches its limit.  That is why we set the capacity we will need upfront so that it will not have to be re-allocated at all in the process.

StringBuilder sb = new StringBuilder(550080);

These are some of the many things to consider when dealing with rather large strings and the concatenating of strings. Overall, we can see that StringBuilder is a lot more performance conscious as well as it will leave less for the garbage collector to clean up in the process.


When to use Break and Continue

This is a fairly simple yet useful difference to know between break and continue when using loops or switch statements. The break statement terminates the closest enclosing loop or switch statement in which it appears. Control is passed to the statement that follows the terminated statement, if any.  The continue statement passes control to the next iteration of the enclosing iteration statement in which it appears.   I find this wording from msdn to be slightly confusing so let’s turn to some examples.

Take this loop for instance:

for (int i = 0; i < 100; i++)
{
    if (i == 0)
    {
        break;
    }

    TestMethod(i);
}

The use of break in the above example causes the loop to exit on the first iteration of the loop. This means that our TestMethod(i) will never be executed.  This works well if you are looking through a list for a particular value, once found, there is no need to iterate through everything else.

Now let’s take a look at the continue statement:

for (int i = 0; i < 10; i++)
{
    if (i == 0)
    {
        continue;
    }

    TestMethod(i);
}

The use of the continue statement above causes the loop to skip calling the TestMethod(i) when i  == 0.  However, the iterations will continue after that and TestMethod(i) will be executed when i  == 1 all the way to i == 99.  This comes in handy if there are certain values in a list that you are not wanting to execute on; you can skip over them and continue on with executing on the rest of the values in the list.

Some closing thoughts, in whether this is best practice or not it’s debating frequently.  The main argument that arises is code readability.  If you are having a hard time reading the code this will raise the chances of you exiting before you are wanting to and can cause bugs that you do not realize.  So as always, make sure you pay attention to what you are doing and what your intent is to ensure that your program is going to perform properly.


Difference Between Ref and Out

The difference between ref and out may not be complicated but easy to mix up. This is really a post mainly for my quick reference and knowledge, but hey, it might pose a quick use for someone else too.

Ref is a keyword that causes an argument to be passed by reference, not by value.  This has an effect of when there is any change to the parameter in the method is reflected in the underlying argument variable in the calling method.   When using the ref keyword, you must use it in the method definition and in the calling method.

class ExampleForRef
{
    static void Main()
    {
        int val = 23;
        RefMethod (ref val);
        Console.WriteLine(val);

        // i = 46
    }

    static void RefMethod(ref int i)
    {
        i = i + 23;
    }
}

A ref parameter must also be initialized before it is passed.  This is a difference between ref and out because when using the out keyword, the variable does not have to be initialized before it is passed.[more]

Out is a keyword that causes arguments to be passed by reference.  This is very similar to what we just discussed above, but when using out, the variable must be initialized before it gets passed. In order to use the out parameter, the method definition and the calling method both must explicitly use the out keyword.

class ExampleForOut
{
    static void Main()
    {
        int value;
        Method(out value);

        // value is now 44
    }

    static void Method(out int i)
    {
        i = 44;
    }
}

A few notes to keep in mind. The called method is required to assign a value before the method can return.  In terms with compiling issues with overloading that may arise, the methods cannot be overloaded if the only difference is the ref and the out. This is taken from msdn:

class CS0663_Example
{
    // Compiler error CS0663: "Cannot define overloaded
    // methods that differ only on ref and out".
    public void SampleMethod(out int i) { }
    public void SampleMethod(ref int i) { }
}

However, if the ref or out parameter is only used in one method than it can be accomplish like this:

class RefOverloadExample
{
    public void SampleMethod(int i) { }
    public void SampleMethod(ref int i) { }
}

class OutOverloadExample
{
    public void SampleMethod(int i) { }
    public void SampleMethod(out int i) { i = 5; }
}

Some ending notes from my research:
-There is no boxing when a value type is passed by reference.
-Properties cannot be passed by ref or out, properties are really methods.


StackOverflow Profile