Tuesday, February 20, 2018

Performance Comparison of Existence Test for a Large Set using Big One Line If vs Else Ifs vs Dictionary Vs Fall Through Case Statement

Below is C# (Sharp) code compares performance for element existence in a large non-sequential set (only 312 elements) using in variety of typical code structures which are;

  1. one line IF (with  ORs) 
  2. multi-line Else Ifs 
  3. Fall Through Case Statement 
  4. Dictionary with Initialization Time
  5. Dictionary Lookup on Key, no init time
  6. Dictionary Lookup on Value, no init time
The live C# Code example below check's if a character is a vowel from a set of 312 Unicode vowels extending to Latin-Supplement Unicode code point.

Note: Under the hood C# compiler creates a dictionary for 6 or more case statements
https://youtu.be/1lnwO63LhRI?t=871

The results are rather surprising!

Friday, February 16, 2018

C# .NET - How to get exact Command (CMD) Line Arguments as Entered by User - Verbatim Echo

So many wrong ways to do this, and they are litter all over Stack Overflow. 

Many solutions follow Microsoft's documentation of iterating over the arguments array and output it as an interpreted string format. This is not necessarily the format that was inputted by the user! 

This is how to get the exact command line arguments as entered by the user.


string AppCMDName = Environment.GetCommandLineArgs()[0]; 
//gets fully qualified application name with or without .exe specified  
//but does not get surrounding double quotes used to qualify the
//cmd line path that may contain spaces. Single quotes not allowed in a path.
string commandLine = Environment.CommandLine.Replace(AppCMDName, "").TrimEnd();
if (commandLine.StartsWith("\"\""))
    commandLine = commandLine.Substring(2, commandLine.Length - 2).TrimStart(); 
    //remove surrounding quotes if used to specify cmd


Typical iteration over args array example from https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/main-and-command-args/how-to-display-command-line-arguments


class CommandLine
{ 
    static void Main(string[] args)
    {
        // The Length property provides the number of array elements
        System.Console.WriteLine("parameter count = {0}", args.Length);

        for (int i = 0; i < args.Length; i++)
        {
            System.Console.WriteLine("Arg[{0}] = [{1}]", i, args[i]);
        }
    }
}
/* Output (assumes 3 cmd line args): 
    parameter count = 3
    Arg[0] = [a]
    Arg[1] = [b]
    Arg[2] = [c]
*/

Thursday, February 15, 2018

C# .NET System.IO.Path.GetExtension vs StringExtension LastIndexOf Performance Comparison

In C#, custom string extensions methods are very powerful and popular feature, but when speed counts, they are not as quick as one would expect. They add overhead of roughly 1ms to the code call. Moreover, in below code speed checks, a by ref call is worse.  

The inline version string extension manipulation is very quick and very close to that of  the Path.GetExtension method.


Update 07/07/2020

This GetFileNameExtension string extension has been update, to work in all unit tests.





Source Code 
In case the above JIT compiler disappears


using System;
using System.IO; 
using System.Diagnostics; 

public static class StringExtension
{    
     /// <summary>
        /// Get filename extension, not ext of . only returns empty string, mirrors Path.GetExtension not try/catch issues by metadataconsulting.blogspot.com
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public static string GetFileNameExtension(this string s)
        {
            string ext = "";
            int fileExtPos = s.LastIndexOf('.');
            if (fileExtPos > s.LastIndexOf('\\'))
            {
                ext = s.Substring(fileExtPos, s.Length - fileExtPos);
                if (ext.Length <= 1) ext = "";
            }
            else
                ext = "";
            return ext;
        }
}
     
public class Program
{
 
 
 public static string GetFileExtStringRef(ref string file) {
  
  //string ext="";
  int fileExtPos = file.LastIndexOf('.');
  if (fileExtPos >  file.LastIndexOf('\\'))
   return file.Substring(fileExtPos, file.Length - fileExtPos);
  else
   return "";
  
  
 }
 
 public static void Main()
 {
  
  //string file = @"c:\foo\bar.cat\cheese.exe.e.x";
  string file = "cheese.log.txt";
  Console.WriteLine("Inline String Manipulation"); 
  Stopwatch s = new Stopwatch();
  s.Start(); 
   string ext = ""; 
   int fileExtPos = file.LastIndexOf('.');
            if (fileExtPos > file.LastIndexOf('\\'))
            {
                ext = file.Substring(fileExtPos, file.Length - fileExtPos);
                if (ext.Length <= 1) ext = "";
            }
            else
                ext = "";
  s.Stop();
  Console.WriteLine(ext+ " in ticks "+ s.ElapsedTicks); 
  
  Console.WriteLine("Native Path.IO Get Extension"); 
  s.Reset();
  s.Start();   
   ext = Path.GetExtension(file); 
  s.Stop(); 
  Console.WriteLine(ext+ " in ticks "+ s.ElapsedTicks); 

  Console.WriteLine("String Extension call"); 
  s.Reset();
  s.Start();   
   ext = file.GetFileNameExtension();
  s.Stop(); 
  Console.WriteLine(ext+ " in ticks "+ s.ElapsedTicks); 

  Console.WriteLine("By Ref Method Call");   
  s.Reset();
  s.Start();   
   ext = GetFileExtStringRef(ref file);
  s.Stop(); 
  
  Console.WriteLine(ext+ " in ticks "+ s.ElapsedTicks); 
  
 }
}