Skip to content

Commit 281d524

Browse files
ClémentClément
authored andcommitted
Improving explanations about clearing in Dictionary.
1 parent 1c2a191 commit 281d524

2 files changed

Lines changed: 18 additions & 1 deletion

File tree

source/code/projects/Dictionary/Dictionary/Dictionary.cs

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -86,6 +86,7 @@ public override string ToString()
8686
return returned;
8787
}
8888

89+
// Clear method
8990
public void Clear()
9091
{
9192
for (int i = 0; i < table.Length; i++)
@@ -206,12 +207,17 @@ public int FindI(TKey keyP)
206207
bool found = false;
207208
int count = 0;
208209
int index = GetIndex(keyP, count);
209-
while (table[index] != null && count <= table.Length && !found)
210+
while (table[index] != null && count < table.Length && !found)
210211
{
211212
if (table[index].Status == StatusType.Active && table[index].Key.Equals(keyP))
212213
{
213214
found = true;
214215
}
216+
else if (table[index].Status == StatusType.Empty)
217+
{
218+
// We can exit, the value will not be found.
219+
count = table.Length;
220+
}
215221
else
216222
{
217223
count++;

source/lectures/data/dictionary.md

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -218,3 +218,14 @@ While the quadratic method hits about 50% of the indices, the double hashing tec
218218

219219
This general discussion relates to performance and requires to measure the dictionary's load factor, which is the number of entries occupied in the hash table divided by the table length (or number of "buckets").
220220
Of course, open-addressed hash table cannot have a load factor greater than 1, but other techniques, such as chaining, allows for larger load factors.
221+
222+
#### Clearing
223+
224+
Clearing the dictionary set all the `Status` to `Empty`:
225+
226+
```{download="./code/projects/Dictionary.zip"}
227+
!include`snippetStart="// Clear method", snippetEnd="// The following is used to compute the"` code/projects/Dictionary/Dictionary/Dictionary.cs
228+
```
229+
230+
We decide to do "object reuse", or *pooling*, so that we can re-use the object instead of deleting it by setting the array to `null` and re-creating `Cell` objects when needed.
231+
This may or may not be a performance gain, based on context, but must be done using `Empty` instead of `Deleted`: otherwise, the `FindI` method may go through many `Cell` that have been cleared instead of deciding more rapidly that a key is missing. The `Add` method, however, already handle this case by having the same behavior for `Deleted` and `Empty` status.

0 commit comments

Comments
 (0)