Thursday, February 15, 2018

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

Custom string extensions method calls are not as quick as you think. It is much slower in comparison to Path.GetExtension method.

I checked these numbers in a VS Project, and seems string extension call is 10 larger when compiled online than compiling the project on my desktop using .NET Framework 4.0 Client Profile? Download vs project solution here, and share your results (don't forget to state .NET  Framework and version you are using).




When the above JIT compiler disappears, this will remain.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
using System;
using System.IO; 
using System.Diagnostics; 

public static class StringExtension
{    
 public static string GetFileExtString(this string file) {
  
  int fileExtPos = file.LastIndexOf('.');
  if (fileExtPos >  file.LastIndexOf('\\'))
   return file.Substring(fileExtPos, file.Length - fileExtPos);
  else
   return "";
 }
}
     
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()
 {
  
  Stopwatch s = new Stopwatch();
  s.Start(); 
  
   //string file = @"c:\foo\bar.cat\cheese.exe.e.x";
      string file = "cheese.log.txt";
   string ext = ""; 
   int fileExtPos = file.LastIndexOf('.');
   int fileLastBackSlash = file.LastIndexOf('\\'); 
   if (fileExtPos > fileLastBackSlash)
    ext = file.Substring(fileExtPos, file.Length - fileExtPos);
   
  s.Stop();
  
  Console.WriteLine(ext+ " in ticks "+ s.ElapsedTicks); s.Reset();
  
  s.Start();   
   ext = Path.GetExtension(file); 
  s.Stop(); 
  
  Console.WriteLine(ext+ " in ticks "+ s.ElapsedTicks); s.Reset();
  
  s.Start();   
   ext = file.GetFileExtString();
  s.Stop(); 
  
  Console.WriteLine(ext+ " in ticks "+ s.ElapsedTicks); s.Reset();
    
  s.Start();   
   ext = GetFileExtStringRef(ref file);
  s.Stop(); 
  
  Console.WriteLine(ext+ " in ticks "+ s.ElapsedTicks); s.Reset();
  
 }
}

No comments:

Post a Comment