Skip to content

Prefer Dictionary<K, V>.TryAddValue(key) over guarded Add(key) #33799

Closed
dotnet/roslyn-analyzers
#6199

Description

@terrajobst

!Dictionary<K, V>.ContainsKey(key) followed by Dictionary<K, V>.Add(key) can be combined into a single TryAdd call.

Category: Performance

Activity

  1. added
    api-suggestion
    code-analyzer
    on Mar 19, 2020
  2. added
    untriaged
    on Mar 19, 2020
  3. added this to the Future milestone on Mar 20, 2020
  4. added
    code-fixer
    on Mar 21, 2020
  5. jeffhandley commented on Mar 21, 2020

    @jeffhandley
    Member

    Estimates:

    • Analyzer: Medium
    • Fixer: Medium
  6. removed
    untriaged
    on Mar 21, 2020
  7. carlossanlop commented on Jan 15, 2021

    @carlossanlop
    Contributor

    Suggested severity: Info

    Cases to cover:

    using System;
    using System.Collections.Generic;
    
    namespace MyNamespace
    {
        public static class MyClass
        {
            static void Main()
            {
                Dictionary<int, int> d = new();
    
                // A) Check the negative returned value
                // Before
                if (!d.ContainsKey(5))
                {
                    d.Add(5, 6);
                }
    
                // After
                d.TryAdd(5, 6);
    
    
                // B) Check the negative returned value and preserve existing logic inside the if body
                // Before
                if (!d.ContainsKey(5))
                {
                    d.Add(5, 6);
                    Console.WriteLine($"Value: {d[5]}");
                }
    
                // After
                if (d.TryAdd(5, 6))
                {
                    Console.WriteLine($"Value: {d[5]}");
                }
    
                // C) Check the positive returned value and preserve existing logic in the else bodyif there's one
                // Before
                if (d.ContainsKey(5))
                {
                    Console.WriteLine($"Value existed: {d[5]}");
                }
                else
                {
                    d.Add(5, 6);
                    Console.WriteLine($"Value added: {d[5]}");
                }
    
                // After
                if (!d.TryAdd(5, 6))
                {
                    Console.WriteLine($"Value existed: {d[5]}");
                }
                else
                {
                    Console.WriteLine($"Value added: {d[5]}");
                }
            }
        }
    }
  8. added
    api-ready-for-review
    and removed
    api-suggestion
    on Jan 15, 2021
  9. GrabYourPitchforks commented on Feb 4, 2021

    @GrabYourPitchforks
    Member

    I'd suggest enabling this analyzer only for scenarios where the associated value is: (a) a literal; or (b) already fully hydrated before the call to ContainsKey. Otherwise you risk a perf regression in scenarios like the following.

    if (!dict.ContainsKey(key))
    {
        dict[key] = ComputeExpensiveValue(); // expensive computation guarded within ContainsKey check
    }

    In theory you could take a factory argument to perform the expensive computation, but now we'd be making callers understand lambdas and closures when all they wanted to do was a simple dictionary access, and I don't think that's a good trade-off for the majority of our developers.

  10. added
    api-approved
    and removed
    api-ready-for-review
    on Feb 4, 2021
  11. terrajobst commented on Feb 4, 2021

    @terrajobst
    ContributorAuthor

    Video

    • Looks good
    • Please consider the comment here.
  12. 2 remaining items

  13. removed
    help wanted
    on Feb 8, 2021
  14. modified the milestones: Future, 7.0.0 on Aug 20, 2021
  15. carlossanlop commented on Jul 6, 2022

    @carlossanlop
    Contributor

    @buyaa-n @CollinAlpert has a PR been merged fixing this? I see there are 3 related issues and more than one related PR but I'm unsure which issues got fixed.

  16. buyaa-n commented on Jul 6, 2022

    @buyaa-n
    Contributor

    Yes this one is fixed

  17. buyaa-n commented on Jul 22, 2022

    @buyaa-n
    Contributor

    Oops, mistaken with #33798, it is not done, reopening

  18. modified the milestones: 7.0.0, Future on Aug 9, 2022
  19. modified the milestones: Future, 8.0.0 on Nov 9, 2022
  20. ghost locked as resolved and limited conversation to collaborators on Jul 29, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

api-approvedarea-System.Collectionscode-analyzercode-fixer

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions