Friday, January 19, 2018

C# .NET System.IO.Path.GetFileName vs LastIndexOf Performance Comparison

Surprise, LastIndexOf can be 10 orders of magnitude slower than Path.GetFileName, if you use  a string "\\"  instead of a character '\\'. 



Code when service will eventually shut down

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


public class Program
{
 public static void Main()
 {
  string path = @"C:\test.txt",filename = ""; 
  Stopwatch x1 = new Stopwatch();
        x1.Start(); 
   filename = path.Substring(path.LastIndexOf("\\") + 1);  
  x1.Stop();
     Console.Write("x1 "+filename+" "); Console.WriteLine(x1.ElapsedTicks+" ticks");   
  Stopwatch x2 = new Stopwatch(); 
  x2.Start(); 
   filename = filename = Path.GetFileName(path);   
  x2.Stop();     
     Console.Write("x2 "+filename+" "); Console.WriteLine(x2.ElapsedTicks+" ticks");   
  Stopwatch x3 = new Stopwatch();
        x3.Start();
   var arr = path.ToCharArray();
   Array.Reverse(arr);
   string rpath = new string(arr);
   int pos = rpath.IndexOf('\\'); 
   filename = rpath.Substring(0, pos); 
   arr = filename.ToCharArray();
   Array.Reverse(arr);
   filename = new string(arr);
  x3.Stop();
     Console.Write("x3 "+filename+" "); Console.WriteLine(x3.ElapsedTicks+" ticks");   
        Stopwatch x4 = new Stopwatch();
        x4.Start(); 
   filename = path.Substring(path.LastIndexOf('\\') + 1);  
  x4.Stop();  
     Console.Write("x4 "+filename+" "); Console.WriteLine(x4.ElapsedTicks+" ticks");   
 }
}

Output

x1 test.txt 54 ticks
x2 test.txt 12 ticks
x3 test.txt 43 ticks
x4 test.txt 5 ticks


1 comment: