Search code examples
c#performancedatabase-designstorage

Tradeoff - Performance vs Space - Boolean vs String Comparison


I'm having a use case to display a modal popup only if there is a content to be shown. Content is configurable in the portal.

  1. Check if content is not empty and then render the modal popup code
    Cons - Performance is low : String check is costly

  2. Introduce a new bit column and make it configurable in the portal to indicate if modal popup needs to be shown.
    Cons - More space : Additional column to store the value

Which approach will you recommend and why?


Solution

  • The premise of your question is incorrect.

    Checking for string.IsNullOrEmpty is actually a very cheap operation, with the following source:

    public static bool IsNullOrEmpty([NotNullWhen(false)] string? value)
    {
        if ((object)value != null)
        {
            return value!.Length == 0;
        }
        return true;
    }
    

    We can prove that this is a quick operation with the following benchmark:

    [MemoryDiagnoser]
    [ShortRunJob]
    public class IsNullOrEmptyBenchmark
    {
        private const string Input = "here is an input";
    
        [Benchmark(Baseline = true)]
        public bool IsNulLOrEmptyBenchmark()
        {
            var isNullOrEmpty = true;
            for (int i = 0; i < 1000; i++)
            {
                isNullOrEmpty = string.IsNullOrEmpty(Input);
            }
    
            return isNullOrEmpty;
        }
    } 
    

    On my machine, this 1000 iteration benchmark (with subsequent assignment) takes a mere 338 ns (a 3rd of an nanosecond per operation, which is essentially a no-op),

    enter image description here

    and most likely is dwarfed by the cost of having to maintain additional data. In addition, whatever code is going to execute the modal will be significantly more expensive than this check.