Is the <TKey, TValue> dictionary adding empty items to the backup storage?

I look through the code for Dictionary<TKey, TValue>. What is interesting in the method private Insertis there bucket, which seems to contain empty slots in an array with a preliminary size. Inside the method, the Insertcode checks to see if there are any elements in the bucket and resize if necessary. The number of elements added is a prime factor. In addition, dictionary entry properties are stored in a structure with a hash code, key, and value.

My question is: what is the purpose? Is this done to prevent attempts to add elements to the dictionary object when sufficient memory may not be available?

NOTE. I did not want to embed any code here, since it requires disassembly for reading.

+3
source share
2 answers

An object Dictionary<TKey,TValue>does not add new null values ​​with this approach. What he does is pre-provisioning of backup storage for data that will be later proposed to be added. The ultimate goal is that the average insert size does not require allocation to complete. Instead, he finds a slot in an existing bucket array to house himself.

The reasons for some of the other points that you mentioned as prime numbers and a hash code are properties common to most hash table style implementations. Instead of going through them each here, I'm going to point you to a wikipedia article on this subject

+1

, , , . " " .

, , "" . , , , .

+1

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


All Articles