Looking to eek-out as much perf as I can from some code (C#) at work, and looking at all the .ToString() manipulations in the code and I came across the following:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static class DateExtensions | |
{ | |
public static string ToSqlDateTime(this System.DateTime dateTime) => dateTime.ToString("yyyy-MM-dd"); | |
} |
How can I quickly workout if I want to do something around this?
BenchmarkDotNet to the rescue, and this library really does make benchmarking easy (and fun!). I created an overload of the extension method which internally uses a cache to avoid the repeative ToString() calls:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static class DateExtensions | |
{ | |
private static readonly ConcurrentDictionary<System.DateTime, string> Cached = new ConcurrentDictionary<System.DateTime, string>(); | |
public static string ToSqlDateTime(this System.DateTime dateTime) => dateTime.ToString("yyyy-MM-dd"); | |
public static string ToSqlDateTimeCached(this System.DateTime dateTime) | |
{ | |
if (Cached.TryGetValue(dateTime, out var value)) | |
return value; | |
value = dateTime.ToSqlDateTime(); | |
Cached.AddOrUpdate(dateTime, _ => value, (_, _) => value); | |
return value; | |
} | |
} |
Only small issue was wanting to test a Static methods, and this only involved creating a wrapper class with annotated methods(calling the static implementations), also preloaded the internal cache:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Instance | |
{ | |
private readonly System.DateTime _date; | |
public Instance() | |
{ | |
_date = new System.DateTime(2022, 08, 10); | |
var date = new System.DateTime(2021, 1, 1); | |
for (var i = 0; i < 100; i++) | |
{ | |
date = date.AddDays(i); | |
date.ToSqlDateTimeCached(); | |
} | |
} | |
[Benchmark] | |
public string CallStaticMethod_ToSqlDateTime() => _date.ToSqlDateTime(); | |
[Benchmark] | |
public string CallStaticMethod_ToSqlDateTimeCached() => _date.ToSqlDateTimeCached(); | |
} |
Results below, make-of-it what you will...
Comments
Post a Comment