Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7997569
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 4, 20262026-06-04T14:59:39+00:00 2026-06-04T14:59:39+00:00

Recently I’ve been experimenting with the use of the Func<T> class, and so far

  • 0

Recently I’ve been experimenting with the use of the Func<T> class, and so far I’m loving it. I’ve noticed however that more and more I’m beginning to use it instead of actually using an instance of T, so I wanted to ask; what’s the overhead of using Func<T> vs T? I know this is a somewhat generic question, as T can be anything, so I guess that question should maybe be focused towards, what is the overhead of passing a function, rather than an instance of a simple object?

For the sake of argument, let’s assume the following.

Our mock object, T

public class Person
{
    private string _name = string.Empty;
    private int _age = 0;
    private bool _isMale = true;

    public Person(string name, int age, bool isMale)
    {
        this.Name = name;
        this.Age = age;
        this.IsMale = isMale;
    }

    public string Name
    {
        get { return this._name; }
        set { this._name = value; }
    }

    public int Age
    {
        get { return this._age; }
        set { this._age = value; }
    }

    public bool IsMale
    {
        get { return this._isMale; }
        set { this._isMale = value; }
    }
}

Now, let’s say we have a pretty extension method on IDictionary, that selects the value by the key, or a default value. The pseudocode could be described as follows:
Is the key found in the KeyValuePair collection
Yes, return the value
No, return the default

Option 1. Our extension method using an instance of T

public static TValue GetValueOrDefault<TKey, TValue>(this IDictionary source, TKey key, TValue @default)
{
    if (source.ContainsKey(key))
    {
        return source[key];
    }
    return @default;
}

// usage
var myValue = myDictionary.GetValueOrDefault("Richard", new Person());

Option 2. Our extension method using Func<T>… mmm, pretty!

public static TValue GetValueOrDefault<TKey, TValue>(this IDictionary source, TKey key, Func<TValue> defaultSelector)
{
    if (source.ContainsKey(key))
    {
        return source[key];
    }
    return defaultSelector();
}

// usage
var myValue = myDictionary.GetValueOrDefault("Richard", () => new Person("Richard", 25, true));

Comparison

Comparing the above options, it’s clear that there are potential benefits of both. Option 1 is slightly easier to read, however I’m currently loving the usage of Func<T>, and therefore to me option 2 seems ideal. I guess I’m considering it a lazily-instantiated parameter, that is only executed when it’s needed, therefore saving on efficiency, but am I right?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-04T14:59:40+00:00Added an answer on June 4, 2026 at 2:59 pm

    This is the code I used for the benchmark:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Linq.Expressions;
    
    namespace ConsoleApplication3
    {
        using System.Collections;
        using System.Diagnostics;
        using System.Globalization;
        using System.Numerics;
        using System.Xml.Linq;
    
        public class Program
        {
    
            public class Person
            {
                private string _name = string.Empty;
    
                private int _age = 0;
    
                private bool _isMale = true;
    
                public Person(string name, int age, bool isMale)
                {
                    this.Name = name;
                    this.Age = age;
                    this.IsMale = isMale;
                }
    
                public string Name
                {
                    get
                    {
                        return this._name;
                    }
                    set
                    {
                        this._name = value;
                    }
                }
    
                public int Age
                {
                    get
                    {
                        return this._age;
                    }
                    set
                    {
                        this._age = value;
                    }
                }
    
                public bool IsMale
                {
                    get
                    {
                        return this._isMale;
                    }
                    set
                    {
                        this._isMale = value;
                    }
                }
            }
    
            private static void Main(string[] args)
            {
                var myDictionary = new Dictionary<string, Person>();
                myDictionary.Add("notRichard", new Program.Person("Richard1", 26, true));
                myDictionary.Add("notRichard1", new Program.Person("Richard2", 27, true));
                myDictionary.Add("notRichard2", new Program.Person("Richard3", 28, true));
                myDictionary.Add("notRichard3", new Program.Person("Richard4", 29, true));
                // usage
                Stopwatch sw = new Stopwatch();
                sw.Start();
                for(int i = 0; i < 100000000; i++)
                {
                    var myValue = myDictionary.GetValueOrDefault("Richard", new Program.Person("Richard", 25, true));
                }
                sw.Stop();
                Console.WriteLine(sw.ElapsedMilliseconds);
                sw = new Stopwatch();
                sw.Start();
                for (int i = 0; i < 100000000; i++)
                {
                    var myValue = myDictionary.GetValueOrDefault("Richard", ()=> new Program.Person("Richard", 25, true));
                }
                sw.Stop();
                Console.WriteLine(sw.ElapsedMilliseconds);
                Console.ReadKey();
            }
        }
        public static class Ex
        {
            public static TValue GetValueOrDefault<TKey, TValue>(this Dictionary<TKey, TValue> source, TKey key, TValue @default)
            {
                if (source.ContainsKey(key))
                {
                    return source[key];
                }
                return @default;
            }
            public static TValue GetValueOrDefault<TKey, TValue>(this Dictionary<TKey, TValue> source, TKey key, Func<TValue> defaultSelector)
            {
                if (source.ContainsKey(key))
                {
                    return source[key];
                }
                return defaultSelector();
            }
    
    
        }
    }
    

    Calling each extenssion method 100000000 times (without finding an entry, hence causing Func to be executed each time) gives the following result:

    T – 10352 ms

    Func<T> – 12268 ms

    Calling each extenssion method 100000000 times (and finding an entry, hence not calling Func at all) gives the following result:

    T – 15578 ms

    Func<T> – 11072 ms

    Hence, which one performs quicker depends of how many instantiations you save and how expensive is each instantiation.

    Optimising the code a bit by reusing the default person instance gives 6809 ms for T and 7452 for Func<T>:

                Stopwatch sw = new Stopwatch();
                var defaultPerson = new Program.Person("Richard", 25, true);
                sw.Start();
                for(int i = 0; i < 100000000; i++)
                {
                    var myValue = myDictionary.GetValueOrDefault("Richard", defaultPerson);
                }
                sw.Stop();
                Console.WriteLine(sw.ElapsedMilliseconds);
                sw = new Stopwatch();
                sw.Start();
                for (int i = 0; i < 100000000; i++)
                {
                    var myValue = myDictionary.GetValueOrDefault("Richard", () => defaultPerson);
                }
    

    So, in theory (if you take instantiation out of the equation), saving a hop in the call stack gives you some performance gain, but in practice, this gain is negligible.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Recently, I was writing a class in which I discovered that I could reduce
Recently, I had the need for a function that I could use to guarantee
Recently I've been doing quite the project mostly working with the DateTime class. Now,..
Recently I've noticed that on occasion I do not get a mayorship notification when
Recently I've been doing things like this: import Tkinter class C(object): def __init__(self): self.root
Recently I noticed (after others have extended the project) that the compile time significantly
Recently we've been getting System.Threading.ThreadAbortExceptions from an ASP.NET webservice that posts data to a
Recently I was asked to develop an app, which basically is going to use
recently I created a java class Custom Layout Manager , which I want to
Recently, I try to build WebKit with VS2012. That cost me a lot of

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.