✅ Am I using NumberFormatInfo properly?

I have a list of ca. 400 numbers which I want to convert to percentage strings as part of an endpoint. I know I will only ever want two decimal places or three decimal places. I was wondering about the impact of allocating a new NumberFormatInfo each time so I whipped up some code:

[Benchmark]
public static string NoCache2() 
{
    return ToPercentageString(0.0433m, 2);
}
[Benchmark]
public static string NoCache3() 
{
    return ToPercentageString(0.0433m, 3);
}
[Benchmark]
public static string Cache2() 
{
    return ToPercentageString2Dp(0.0433m);
}
[Benchmark]
public static string Cache3() 
{
    return ToPercentageString3Dp(0.0433m);
}

public static string ToPercentageString(decimal d, int decimalPlaces) 
    => d.ToString(
        "P",
        new NumberFormatInfo()
        {
            PercentDecimalDigits = decimalPlaces,
            PercentPositivePattern = 1
        }
    );
    
public static string ToPercentageString2Dp(decimal d) 
    => d.ToString("P", TwoDpFormat);

public static string ToPercentageString3Dp(decimal d) 
    => d.ToString("P", ThreeDpFormat);

private static readonly NumberFormatInfo TwoDpFormat = new NumberFormatInfo()
{
    PercentDecimalDigits = 2,
    PercentPositivePattern = 1
};

private static readonly NumberFormatInfo ThreeDpFormat = new NumberFormatInfo()
{
    PercentDecimalDigits = 3,
    PercentPositivePattern = 1
};


The results indicate caching is better but the end result after all the numbers in terms of allocs or nanoseconds saved seems unlikely to be significant (probably 217kB memory saved, or 12 microseconds faster). Is this premature optimization? OR is there a more idiomatic way to use NumberFormatInfo that I'm missing here?
Was this page helpful?