Skip to content

Commit 7c000c6

Browse files
illusory0x0peter-jerry-ye
authored andcommitted
perf(@sorted_map.each) replace stack version with dfs version
1 parent c2d0c65 commit 7c000c6

File tree

1 file changed

+11
-25
lines changed

1 file changed

+11
-25
lines changed

sorted_map/map.mbt

Lines changed: 11 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -124,39 +124,25 @@ pub fn clear[K, V](self : T[K, V]) -> Unit {
124124
///|
125125
/// Iterates the map.
126126
pub fn each[K, V](self : T[K, V], f : (K, V) -> Unit) -> Unit {
127-
let s = []
128-
let mut p = self.root
129-
while not(p.is_empty()) || not(s.is_empty()) {
130-
while not(p.is_empty()) {
131-
s.push(p)
132-
p = p.unwrap().left
133-
}
134-
if not(s.is_empty()) {
135-
p = s.unsafe_pop()
136-
f(p.unwrap().key, p.unwrap().value)
137-
p = p.unwrap().right
127+
fn dfs(root : Node[K, V]?) -> Unit {
128+
if root is Some(root) {
129+
dfs(root.left)
130+
f(root.key, root.value)
131+
dfs(root.right)
138132
}
139133
}
134+
135+
dfs(self.root)
140136
}
141137

142138
///|
143139
/// Iterates the map with index.
144140
pub fn eachi[K, V](self : T[K, V], f : (Int, K, V) -> Unit) -> Unit {
145-
let s = []
146-
let mut p = self.root
147141
let mut i = 0
148-
while not(p.is_empty()) || not(s.is_empty()) {
149-
while not(p.is_empty()) {
150-
s.push(p)
151-
p = p.unwrap().left
152-
}
153-
if not(s.is_empty()) {
154-
p = s.unsafe_pop()
155-
f(i, p.unwrap().key, p.unwrap().value)
156-
p = p.unwrap().right
157-
i += 1
158-
}
159-
}
142+
self.each(fn(k, v) {
143+
f(i, k, v)
144+
i = i + 1
145+
})
160146
}
161147

162148
///|

0 commit comments

Comments
 (0)