c# - Hashset First() + Remove() performance -
i encountered performance issue today involving hashset.remove , i'm still unclear on problem was. question i'm left is, why approach2
method faster approach1
method? i'm assuming it's calls hashset.remove msdn docs hashset.remove o(1).
public class hashsettester { int testnum = 20000; public void run() { var hashset2 = createtesthashset(); var watch2 = new stopwatch(); watch2.start(); approach2(hashset2); watch2.stop(); var hashset1 = createtesthashset(); var watch1 = new stopwatch(); watch1.start(); approach1(hashset1); watch1.stop(); console.writeline("approach1 {0:0.0}x slower approach2", watch1.elapsed.totalseconds / watch2.elapsed.totalseconds); } hashset<object> createtesthashset() { var result = new hashset<object>(); var rnd = new random(); (int = 0; < testnum; i++) { result.add(rnd.next()); } return result; } void approach1(hashset<object> hashset) { while (hashset.any()) { var instance = hashset.first(); hashset.remove(instance); dosomething(instance, hashset); } } void approach2(hashset<object> hashset) { var tempitems = new list<object>(); while (hashset.any()) { tempitems.clear(); tempitems.addrange(hashset); hashset.clear(); foreach (var instance in tempitems) { dosomething(instance, hashset); } } } void dosomething(object obj, hashset<object> hashset) { // in cases, hashset added here } public static void main() { new hashsettester().run(); } }
if need every entry of hashset , remove entries why not use linq instead?
hashset.foreach(item => dosomething(item, hashset)); hashset.clear();
this give acceptable performance when dealing big collections.
Comments
Post a Comment