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); 
  
 }
}

No comments:

Post a Comment