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 6342207
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 24, 20262026-05-24T20:11:49+00:00 2026-05-24T20:11:49+00:00

I wrote the following extension method to get an element from a dictionary, or

  • 0

I wrote the following extension method to get an element from a dictionary, or null if the key isn’t present:

public static TValue ItemOrNull<TKey, TValue>(this IDictionary<TKey, TValue> dict, TKey key)
{
    try
    {
        return dict[key];
    }
    catch (KeyNotFoundException ex)
    {
        return default(TValue);
    }
}

I noticed that my program was running very slowly so I tracked down the problem to this extension method using a high precision timer class. I get similar results ~100 times in a row:

DebugTimer.ResetTimer();
    dict1.ItemOrNull(key);
    dict2.ItemOrNull(key);
DebugTimer.StopTimer();

takes about 110,000,000 ticks (more than 0.03 seconds on my processor). While the more verbose version:

DebugTimer.ResetTimer();
    if (dict1.ContainsKey(key))
        y = dict1[key];
    if (dict2.ContainsKey(key))
        z = dict2[key];
DebugTimer.StopTimer();
MessageBox.Show(y.ToString(), z.ToString()) // so the compiler doesn't optimize away y and z

takes about 6,000 ticks (less than 0.000002 seconds).

Is it clear to anyone why my extension method version is taking more than 4 orders of magnitude longer than the verbose version?

  • 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-05-24T20:11:51+00:00Added an answer on May 24, 2026 at 8:11 pm

    Don’t catch exceptions for flow control – it’s not just that it can cause performance problems (although they’re not nearly as bad as most people think – as Eric says, most people’s fear of exception performance comes from using the debugger). It’s more about the logical nature of exceptions. Personally I wouldn’t use exceptions in this way even if they were essentially free.

    Has anything bad happened here? Is it in any way invalid for the user to be asking for this key’s value? Absolutely not – the whole purpose of the method is to provide a default. It’s not exceptional for the key to be absent – so you should look for a way of working without exceptions.

    Now Dictionary<,> already has a method to let you fetch a value if the key exists and let you know whether or not it was found: TryGetValue.

    public static TValue GetValueOrDefault<TKey, TValue>(
        this IDictionary<TKey, TValue> dict,
        TKey key)
    {
        TValue ret;
        // We don't care about the return value - we want default(TValue)
        // if it returns false anyway!
        dict.TryGetValue(key, out ret);
        return ret;
    }
    

    Extension methods are just compiled into regular static method calls and thus have no performance difference to them.

    You might also want to add an overload allowing the user to express the default value to return if the key wasn’t found:

    public static TValue GetValueOrDefault<TKey, TValue>(
        this IDictionary<TKey, TValue> dict,
        TKey key, TValue defaultValue)
    {
        TValue ret;
        return dict.TryGetValue(key, out value) ? ret : defaultValue;
    }
    

    I’ve adjusted the name of your method to match TryGetValue, by the way. Obviously you don’t have to follow that – it’s just a suggestion.

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

Sidebar

Related Questions

I have an extension method with the following signature: public static Expression<Func<T, bool>> And<T>(this
Using an idea from Bob King idea I wrote the following method. It works
I have created an extension method called AddGZip which looks like the following: public
Let's say I have the following method: public static int CountNonNullMembers<T>(this IEnumerable<T> enumerable) {
I wrote the following extension methods for Session so that I can persist and
I have the following class and extension class (for this example): public class Person<T>
I have the following class hierarchy class Test { public string Name { get;
Wrote the following in PowersHell as a quick iTunes demonstration: $iTunes = New-Object -ComObject
I wrote the following javascript to put in my startup folder to work around
I wrote the following Nant script on my Vista dev machine and was pleased

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.