private void btnObjRef_Click(object sender, EventArgs e) { const int CNT = 8; const int SEARCHES = 8000000; var rnds = new int[800]; for (var i = 0; i < rnds.Length; i++) { rnds[i] = Ambient.Random.NextScaledRandomInteger(CNT / 2, CNT - 1); } var lst = new Perzon[CNT]; var dict = new Dictionary <object, int>(128, Azos.Collections.ReferenceEqualityComparer <object> .Default); for (var i = 0; i < lst.Length; i++) { var person = new Perzon(); lst[i] = (person); dict.Add(person, i); } var found1 = 0; var found2 = 0; System.Threading.Thread.SpinWait(250333000); var sw = Stopwatch.StartNew(); for (var j = 0; j < SEARCHES; j++) { var key = this;//WORST CASe, key is never found //lst[rnds[j%rnds.Length]]; for (var i = 0; i < lst.Length; i++) { if (object.ReferenceEquals(key, lst[i])) { found1++; break;//FOUND!!! } } } var time1 = sw.ElapsedMilliseconds; sw.Restart(); for (var j = 0; j < SEARCHES; j++) { var key = this;//WORST CASe, key is never found //lst[rnds[j%rnds.Length]]; int idx; if (dict.TryGetValue(key, out idx)) { found2++; //FOUND! } } var time2 = sw.ElapsedMilliseconds; var summary = @" Elements: {0} Searched: {1} ------------------------------------- Linear search found {2} in {3} ms at {4:n2} ops/sec Dict search found {5} in {6} ms {7:n2} ops/sec ".Args( CNT, SEARCHES, found1, time1, SEARCHES / (time1 / 1000d), found2, time2, SEARCHES / (time2 / 1000d) ); MessageBox.Show(summary); }
private void btnObjRef_Click(object sender, EventArgs e) { const int CNT = 8; const int SEARCHES = 8000000; var rnds = new int[800]; for(var i=0; i<rnds.Length; i++) rnds[i] = ExternalRandomGenerator.Instance.NextScaledRandomInteger(CNT / 2, CNT-1); var lst = new Perzon[CNT]; var dict = new Dictionary<object, int>(128, ReferenceEqualityComparer<object>.Instance); for(var i=0; i<lst.Length; i++) { var person = new Perzon(); lst[i] = (person); dict.Add(person, i); } var found1 = 0; var found2 = 0; System.Threading.Thread.SpinWait(250333000); var sw = Stopwatch.StartNew(); for(var j=0; j<SEARCHES; j++) { var key = this;//WORST CASe, key is never found //lst[rnds[j%rnds.Length]]; for(var i=0; i<lst.Length; i++) if ( object.ReferenceEquals(key, lst[i])) { found1++; break;//FOUND!!! } } var time1 = sw.ElapsedMilliseconds; sw.Restart(); for(var j=0; j<SEARCHES; j++) { var key = this;//WORST CASe, key is never found //lst[rnds[j%rnds.Length]]; int idx; if (dict.TryGetValue(key, out idx)) found2++; //FOUND! } var time2 = sw.ElapsedMilliseconds; var summary= @" Elements: {0} Searched: {1} ------------------------------------- Linear search found {2} in {3} ms at {4:n2} ops/sec Dict search found {5} in {6} ms {7:n2} ops/sec ".Args( CNT, SEARCHES, found1, time1, SEARCHES / (time1 / 1000d), found2, time2, SEARCHES / (time2 / 1000d) ); MessageBox.Show( summary ); }