Skip to content

Commit ece680d

Browse files
FlyCloudCpeter-jerry-ye
authored andcommitted
refactor(set): prevent rehashing
1 parent 4b65e4a commit ece680d

File tree

1 file changed

+11
-2
lines changed

1 file changed

+11
-2
lines changed

set/linked_hash_set.mbt

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -70,7 +70,12 @@ pub fn[K] Set::new(capacity? : Int = 8) -> Set[K] {
7070
/// Create a hash set from array.
7171
#as_free_fn
7272
pub fn[K : Hash + Eq] Set::from_array(arr : Array[K]) -> Set[K] {
73-
let m = Set::new(capacity=arr.length())
73+
let length = arr.length()
74+
let mut capacity = length.next_power_of_two()
75+
if length >= calc_grow_threshold(capacity) {
76+
capacity *= 2
77+
}
78+
let m = Set::new(capacity~)
7479
arr.each(e => m.add(e))
7580
m
7681
}
@@ -453,7 +458,11 @@ pub impl[K : Hash + Eq] Eq for Set[K] with equal(self, other) {
453458
#as_free_fn
454459
pub fn[K : Hash + Eq] Set::of(arr : FixedArray[K]) -> Set[K] {
455460
let length = arr.length()
456-
let m = Set::new(capacity=length)
461+
let mut capacity = length.next_power_of_two()
462+
if length >= calc_grow_threshold(capacity) {
463+
capacity *= 2
464+
}
465+
let m = Set::new(capacity~)
457466
for i in 0..<length {
458467
let e = arr[i]
459468
m.add(e)

0 commit comments

Comments
 (0)