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 for SEO and 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"; 
  string filename = ""; 
  
  Stopwatch x1 = new Stopwatch();
  x1.Start(); 
   filename = path.Substring(path.LastIndexOf("\\") + 1);  
  x1.Stop();        
          
  Console.WriteLine(x1.ElapsedTicks); 
  
  Stopwatch x2 = new Stopwatch();
  x2.Start(); 
   filename = filename = Path.GetFileName(path);   
  x2.Stop();
     
  Console.WriteLine(x2.ElapsedTicks); 
  
  Console.WriteLine(filename);
 }
}
Results
42 ticks
8 ticks
test.txt

1 comment: