Sometimes when we want to reuse a Dictionary, we can Clear () or directly create a new object,
Which of the two is cost-effective?
Let's look at the program:
private void Experiment() { System.Diagnostics.Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); //Dictionary
aa = new Dictionary
(); for (var loop = 0; loop < 30000; loop++) { Dictionary
aa = new Dictionary
(); for (var i = 0; i < 10000; i++) { aa.Add(i,i); } //aa.Clear(); } stopwatch.Stop(); Console.WriteLine("All timeL:"+stopwatch.Elapsed.TotalSeconds); }
The data result is as follows:
Use Clear () for 6 seconds. The time for using the new object method is 20 seconds.
Because the NEW object scheme requires many Resize operations.
The basic class code for these things is as follows:
The Add operation is as follows:
public void Add(TKey key, TValue value) { this.Insert(key, value, true); }
The code for calling the Insert operation is as follows:
Private void Insert (TKey key, TValue value, bool add) {int freeList; if (key = null) {ThrowHelper. throwArgumentNullException (ExceptionArgument. key);} if (this. buckets = null) {this. initialize (0);} int num = this. comparer. getHashCode (key) & 0x7fffffff; int index = num % this. buckets. length; for (int I = this. buckets [index]; I> = 0; I = this. entries [I]. next) {if (this. entries [I]. hashCode = num) & this. comparer. equals (this. entries [I]. key, key) {if (add) {ThrowHelper. throwArgumentException (ExceptionResource. argument_AddingDuplicate);} this. entries [I]. value = value; this. version ++; return ;}if (this. freeCount> 0) {freeList = this. freeList; this. freeList = this. entries [freeList]. next; this. freeCount --;} else // The hash is full {if (this. count = this. entries. length) {this. resize (); // reopens a memory space index = num % this for the hash. buckets. length;} freeList = this. count; this. count ++;} this. entries [freeList]. hashCode = num; this. entries [freeList]. next = this. buckets [index]; this. entries [freeList]. key = key; this. entries [freeList]. value = value; this. buckets [index] = freeList; this. version ++ ;}
Resize () is as follows:
Private void Resize () {int prime = HashHelpers. getPrime (this. count * 2); int [] numArray = new int [prime]; // open up a new array for (int I = 0; I <numArray. length; I ++) {numArray [I] =-1;} Entry
[] DestinationArray = new Entry
[Prime]; // open up a new Array. copy (this. entries, 0, destinationArray, 0, this. count); for (int j = 0; j <this. count; j ++) {int index = destinationArray [j]. hashCode % prime; destinationArray [j]. next = numArray [index]; numArray [index] = j;} this. buckets = numArray; this. entries = destinationArray ;}
In the next example, we recommend that you use the clear () method to repeat the structures that may be resize (), such as dictionary and Arraylist. Because resize () is a waste of time