How to optimize C # dictionary update with one key search?

Say for example, I have

Dictionary<string, double> foo;

I can do

foo["hello"] = foo["hello"] + 2.0

Or I could do

foo["hello"] += 2.0

but the compiler just extends it to the above code. I checked that using JetBrains.Peek to see builds.

This seems wasteful since two key queries are required to upgrade. Is there a dictionary implementation that can do this in a single search? Note. I use a dictionary to store 100 thousand. Elements of the geometry of information from the grid, and the search is performed in the inner loop. Please do not reply "premature optimization is the root of all evil". :)

Yes, I have profiled.

enter image description here

+4
source share
3 answers

, , , , :

, .

.

:

  • GetHashCode
  • , .
  • ( ref)

, :

  • .

.

@George Duckett . ref :

var hello = foo["hello"]; 
hello.howAreYou += 2.0;

, , .

+2

ConcurrentDictionary, ConcurrentDictionary.AddOrUpdate, , . .

, , , . , , .

+1

, . bradgonesurfing, , , , .

, , . ? 100k 1MB . , .

+1

Source: https://habr.com/ru/post/1524229/


All Articles