rulururu

post Shorten a Path

June 25th, 2008

Filed under: .NET — Kai @ 7:36 pm

Sometimes you need a long path to be short because the field that displays the text doesn’t have enought space for the whole path.

This in .NET written function does cut “C:\Windows\System32\Test\Test.dll” to “C:\Windows\…\Test.dll”.

First parameter is the path that has to be shorten.
Second parameter is the maximum length of the new string.
Third parameter is the Font that is used.
Return value is the new storten string.

public string PathShorten(string Path, int Length, Font TextFont)
{
    string[] PathParts = Path.Split('\\');
    StringBuilder PathBuild = new StringBuilder(Path.Length);
    string LastPart = PathParts[PathParts.Length - 1];
    string PrevPath = "";
 
    //check if path is already shorter than max. length
    if (TextRenderer.MeasureText(Path, TextFont).Width < Length)
        return Path;
 
    for (int i = 0; i < PathParts.Length - 1; i++)
    {
        PathBuild.Append(PathParts[i] + @"\");
        if (TextRenderer.MeasureText(PathBuild.ToString() + @"...\" 
              + LastPart, TextFont).Width >= Length)
            return PrevPath;
        else
            PrevPath = PathBuild.ToString() + @"...\" + LastPart;
    }
    return PrevPath;
}

Just a simple snipped but I guess that it can often be valuable. I hope it can be used widely.

post Avoid making useless new object

June 4th, 2008

Filed under: .NET, C++ — Kai @ 3:16 pm

You often see statements like the one here when programmers want to check if a string has value or not.

if(strName!="")
{ ... }

For C++ programmers (who uses CString for example) this is correct and not really unusual - but please if you’re writing code in C# or another .NET language keep in mind that this causes the allocation of a new String object just for the reason to compare it with an empty string.

Correct implementations would be:

if(strName.Length <= 0)
{ ... }
 
if(strName.Length == 0)
{ ... }

You will not regognize this in a performance test or when using the application but it’s just good form to do it right - also because you know why you should do.

When working with CStrings it’s dispensable faster or slower to compare with an empty string or just to compare the length. If you have a look at the IsEmpty() member function of CString Class you’ll mention that I’m right:

bool IsEmpty() const throw()
{
     return( GetLength() == 0 );
}

post Question of Recursion

May 22nd, 2008

Filed under: .NET, C++, General Programming — Kai @ 2:53 pm

Algorithms can often be implemented recursively or nonrecursively; the decision rests with the programmer, who might shy away from a recursive solution because the algorithm might not terminate or that performance might be poor. In reality, recursion can allow for very elegant code as well as facilitating an interesting and economical type of code reuse.

Iterative algorithms, especially those with a loop, can usually be easily rewritten to use recursive function calls instead of loops. In some cases it’s a bad idea because the iterative version is usually simpler, faster, and uses less memory.

The classical scenario for recursion was search algorithms, factorial calculations, and so on. A well-know algorithmn that uses recursion is Binary Search.

This recursive version checks to see if we’re at the key (in which case it can return), otherwise it calls itself so solve a smaller problem, ie, either the upper or lower half of the array.

int BinarySearch(int iSortedArray[], int iFirst, int iLast, int iKey) 
{
   if (iFirst <= iLast) {
       int iMid = (iFirst + iLast) / 2;  
       if (iKey == iSortedArray[iMid]) 
           return iMid;  
       else if (iKey < iSortedArray[iMid]) 
           return BinarySearch(iSortedArray, iFirst, iMid-1, iKey);
       else
           return BinarySearch(iSortedArray, iMid+1, iLast, iKey);
   }
   return -(iFirst+ 1);    // failed to find key
}

Besides elegant code design recursion can be the reason for some problems.
Recursion isn’t safe in C/C++ because there is no reasonable way to deal with running out of call stack space. Even if you dynamically allocate stack frames from the heap, you still can run out of heap and how do you handle the error then?

You might convert the failed call stack allocation into an exception that unwinds the stack until an out-of-stack exception handler is found, but the problem is that any function in any library called from a recursive routine might be the call that blows the stack.

Fortunately any algorithm that can be written recursively can be rewritten iteratively by keeping a heap-based stack object (and if it can be written completely tail-recursively, you don’t even need a stack). The code might be uglier when written iteratively, but it’s always possible.

You’d defenetly use recusion when you can guarantee two things:

  • Each recursive step breaks down the problem into a smaller problem of the same type.
  • Each recursive step reduces the problem significantly.

The first is a general rule of recursion. If each step doesn’t break the problem down into a smaller problem of the same type, it’s harder to write a recursive function and guarantee that it will terminate. The second is kinda personal guideline. I generally won’t write a recursive function unless it divides the problem in half with each step. This way I can verify with relative ease that the algorithm will be efficient.

Originally I planted to write this post about anonymous recursion with lambda in c#, but then I decited to describe recursion basics a bit more in detail.

A simple recursive function in c# would be for example:

private static double pow(double var, double n)
{
    if(n == 0)
        return 1;
    else
        return var * pow(var, n - 1);
}

Anonymous recursion is a recursion technique that uses anonymous functions.
I got the idea to define a special delegate type for self-applicable functions:

delegate T Pow<T>(Pow<T> self);

The delegate above can be defined like this:

Pow<double> myPow = f => f(f);
 
myPow(myPow);

When myPow is being applied to itselfwill apply myPow to itself, which will … infinite recursion. While not particularly useful in this setting, the example demonstrates that you can in fact have recursive application in a lambda expression. Now all we have to do is to make it do something useful as it goes, such as call functions recursively.

Recursion is beautiful and lambdas are the ultimate abstraction. But that’s too much for now…I’ll write about that sometime.

post SP 1 (Beta) for Visual Studio 2008 and .NET Framework 3.5

May 14th, 2008

Filed under: .NET, Visual Studio — Kai @ 1:33 pm

As I recently have experienced a few days ago the first beta version of the service pack 1 for Visual Studio 2008 and .NET Framework 3.5 have been released.

The release of the final version is announced for summer.

This servicing updates provide a roll-up of bug fixes and performance improvements.
Furthermore, additions and enhancements that make building .NET applications have become better.

The parts that provide development with C++/MFC won’t have many new features but C# development is said to be improved.

In any case you’d be aware of:

  • Users that have Windows Vista should have SP1 for Vista installed before upgrading the .NET 3.5 Framework with SP1.
  • Any users who still work with beta of Visual Studio 2008 (Codename Orcas I think) will get in trouble when trying to install the service pack. A detailed step-guide can be found here.
  • There is a change in behavior in the .NET 3.5 SP1 beta that causes a problem with the shipping versions of Expression Blend (WYSIWYG-Editor für XAML). The recommented way to work around this issue is to download the recently updated version of Blend 2.5.

At least bear in mind “be careful - it’s still beta form”. The usage on critical system is not recommented yet.

Scott Guthrie (Corporate Vice President der Microsoft Developer Division) has done a great blog post that shows the improvments in detail.
It can be found here.

The Visual Studio SP1 Beta is quite extensive and includes support for SQL Server 2008, new ADO.NET features, improvements to the WPF designers, WCF templates for Silverlight projects, debugger support for the .NET Framework public symbols and source release, control improvements and Visual C++ improvements such as the Office 2007 Ribbon bar.

post Tipps for writing good performanced code in .NET

May 6th, 2008

Filed under: .NET, General Programming — Kai @ 5:50 pm

Writing code that runs quickly is sometimes at odds with writing code quickly.

Writing unnecessary code is undoubtedly bad for work efficiency. However, it’s important to realize that different situations have different needs. Code for vehicular real-time control systems has inherent up-front responsibilities for stability and performance that aren’t present in, say, a small one-off departmental application. Therefore, it’s more important in such code to optimize early and often.

  • 1. Tools
  • While testing tools such as NUnit and the upcoming VS.NET 2005 Team System can help you find bottlenecks, when tuning small sections of code, there’s still no substitute for the micro-benchmark. This is because most generic testing frameworks depend on things like delegates, attributes, and/or interface method calls to do testing, and the code usually is not written with benchmarking primarily in mind. This can be very significant if you’re interested in measuring the execution time of a batch of code down to the microsecond or even nanosecond level.
    However, these techniques alone can’t solve the dreaded problem of uniformly slow code, which surfaces when large bottlenecks have been resolved but the code still exhibits inadequate performance. This is code that has been written without attention to correct usage.

    Another important tool is ildasm.exe, the IL disassembler. With it, you can inspect the IL of your release builds to see if your assumptions are correct about what’s going on under the covers.
    A great free tool for decompiling IL to C# or VB source, Reflector, can be found [here]; it’s incredibly useful for viewing code that ships with the .NET Framework, for those of you less familiar with IL.

  • 2. Techniques & Guides Lines
  • 2.1 Objects and Garbage Collectors
    Objects are expensive to use, partly because of the overhead involved in allocating memory from the heap (which is actually well-optimized in .NET) and partly because every created object must eventually be destroyed. The destruction of an object may take longer than its creation and initialization, especially if the class contains a custom finalization routine.

    It’s necessary to understand garbage collection to appreciate the full impact of using objects. The single most important fact to know about the garbage collector is that it divides objects into three “generations”: 0, 1, and 2. Every object starts out in generation 0; if it survives (if at least one reference is maintained) long enough, it goes to 1; much later, it transitions to 2. The cost of collecting an object increases with each generation. For this reason, it’s important to avoid creating unnecessary objects, and to destroy each reference as quickly as possible. The objects that are left will often be long-lived and won’t be destroyed until application shutdown.

    2.2 Lazy Instantiation / Initialization
    The Singleton design pattern is often used to provide a single global instance of a class. Sometimes it’s the case that a particular singleton won’t be needed during an application run.
    It’s generally good practice to delay the creation of any object until it’s needed, unless there’s a specific need to the contrary - for instance, to pre-cache slow-initializing objects such as database connections. The “double-checked locking” pattern is useful in these situations, as a way to avoid synchronization and still ensure that a needed action is only performed once. Lazy initialization is a technique that can enhance the performance of an entire application through object reduction.

    2.3 Avoiding Useage of Class Destructors
    Class destructors cause extra overhead for the garbage collector, ’cause it must track which objects have been finalized before their memory can be reclaimed.

    2.4 Casting and Boxing / Unboxing Overhead
    Casting is the dynamic conversion of a type at runtime to another, and boxing is the creation of a reference wrapper for a value type (unboxing being the conversion back to the wrapped value type).
    The overhead of both is most heavily felt in collections classes, as they all - with the exception of certain specialized ones like StringDictionary - store each value as an Object. For instance, when you store an Int32 in an ArrayList, it is first boxed (wrapped in an object) when it is inserted; each time the value is read, it is unboxed before it is returned to the calling code.

    One soloution is to use generics, the other how to avoid overhead is to avoid it by creating strongly typed collections and by typing variables and parameters as strongly as possible. If you’re unsure about whether or not boxing/unboxing is taking place, you can check the IL of your code for appearances of the box and unbox keywords.

    2.5 Trusting the Garbage Collector
    Programmers new to .NET sometimes worry about memory allocation to the point that they explicitly invoke System.GC.Collect(). Garbage collection is a fairly expensive process, and it usually works best when left to its own devices. A thumb rule is not to call GC.Collect() unless you really know what you’re doing.

    2.6 Excessive use of Delegates
    Delegates are slower to execute than interface methods. Delegates are often used to introduce a level of indirection in code, but in almost all cases interfaces allow a cleaner design. Don’t use them if it’s not necessary.

    2.7 Using the ‘Sealed’ Keyword
    Wherever extensibility is not required, you should use the sealed keyword. This makes your design easier to understand, as someone can tell at a glance if a certain class or method isn’t meant to be extended or overridden. It also increases the chances that the compiler will inline code.

    2.8 for versus foreach
    The rumor abounds that the foreach loop is bad for performance. The truth is actually a little more complicated. Basically, foreach involves no performance penalty when used against arrays. However, when used against lists it involves the same overhead as creating an enumerator and using it within a try/catch block!

    2.8 Working With Strings
    Don’t Use String.Format() to Concatenate Strings.
    While string-formatting routines built into .NET are very useful for globalization and other tasks, they’re not meant to be used for appending strings to each other. You’d better prefer Stringbuilders as I explained in this post.

    2.9 Minimizing Synchronized Blocks
    The use of the [MethodImpl Attribute(MethodImplOptions.Synchronized)] attribute should be avoided, as it always locks an entire method and is also non-standard C# usage. Instead, the lock keyword or one of the System.Threading classes should be used. Wherever possible, adjust the start of a synchronized section forward and the end backward. Do whatever you can to decrease the number of synchronized operations.

    Do early optimization before rewriting half of your project afterwards but don’t waste too much time in optimizing parts of code that don’t make problems now. It’s never false thinking of writing a quick running code than just writing it down quick but don’t agonize over things that don’t make problems yet.

    post Best Practice: Avoid using const on read-only variables

    April 22nd, 2008

    Filed under: .NET — Kai @ 9:59 am

    I often mention the blindfold use of readonly and const keyword in C#. In general you can say that const variables get the value assigned at Compile time and are unchangeable once established. In opposite to that readonly variable get the value assigned at run time and are unchangeable once established.

    A quick synopsis on the differences between ‘const’ and ‘readonly’:

    const

    • Can’t be static.
    • Value is evaluated at compile time.
    • Initiailized at declaration only.

    readonly

    • Can be either instance-level or static.
    • Value is evaluated at run time.
    • Can be initialized in declaration or by code in the constructor.

    For a const thist would be typical:

    public class MyClass
    {
      public const double PI = 3.14159;
    }

    PI cannot be changed in the application anywhere else in the code as this will cause a compiler error.

    Constants must be of an integral type (sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double, decimal, bool, or string), an enumeration, or a reference to null.

    Constants can be marked as public, private, protected, internal, or protected internal.

    As mentioned above a readonly can be assigned at run time. Due to that this is allowed:

    public class MyClass
    {
      public readonly double PI;
     
      public MyClass()
      {
        PI = 3.14159;
      }
    }

    A C# guideline defines that the best practise is to avoid const on read-only variables, therefor use the readonly keyword.

    The reason why is very simple. Lets say you have the following code in a class library:

    public class ServiceClass
    {
        public const int MyConst = 12;
        public readonly int MyReadOnlyVar = 10;
    }

    And you have the following code in another assembly calling the code above.

    ServiceClass service = new ServiceClass();
     
    int someValue = ServiceClass.MyConst;
     
    someValue = service.MyReadOnlyVar;

    You deploy both the class library and the assembly calling it. After deployment, a change is being made to the class library. you change the values of MyConst to 15 and MyReadOnlyVar to 15. You now release the class library and life is good. Is it?

    What’s the values of someValue in the two statements below after the second release of the class library?

    int someValue = ServiceClass.MyConst;
     
    someValue = service.MyReadOnlyVar;

    Initially, when the compiler sees the line

    int someValue = ServiceClass.MyConst;

    it replaces ServiceClass.MyConst with 12.

    At runtime the class library is not called for the value since it is a constant. As a result of this, the code calling into the class library is not aware that the value of ServiceClass.MyConst has changed. It will continue to use the old value 12 while the new value of MyConst is 15.

    ruldrurd
    « Previous PageNext Page »
    Powered by WordPress, Content and Design by Kai Bellmann
    Entries (RSS) and Comments (RSS)