Skip to content

Commit 4b65e4a

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

File tree

1 file changed

+9
-0
lines changed

1 file changed

+9
-0
lines changed

builtin/linked_hash_map.mbt

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,11 @@ pub fn[K, V] Map::new(capacity? : Int = 8) -> Map[K, V] {
6868
///|
6969
/// Create a hash map from array.
7070
pub fn[K : Hash + Eq, V] Map::from_array(arr : Array[(K, V)]) -> Map[K, V] {
71+
let length = arr.length()
72+
let mut capacity = length.next_power_of_two()
73+
if length >= calc_grow_threshold(capacity) {
74+
capacity *= 2
75+
}
7176
let m = Map::new(capacity=arr.length())
7277
arr.each(e => m.set(e.0, e.1))
7378
m
@@ -623,6 +628,10 @@ pub impl[K : Hash + Eq, V : Eq] Eq for Map[K, V] with equal(
623628
///|
624629
pub fn[K : Hash + Eq, V] Map::of(arr : FixedArray[(K, V)]) -> Map[K, V] {
625630
let length = arr.length()
631+
let mut capacity = length.next_power_of_two()
632+
if length >= calc_grow_threshold(capacity) {
633+
capacity *= 2
634+
}
626635
let m = Map::new(capacity=length)
627636
// arr.iter((e) => { m.set(e.0, e.1) })
628637
for i in 0..<length {

0 commit comments

Comments
 (0)