Skip to content

Commit 869e957

Browse files
committed
perf: improve @list.from_iter use one pass
1 parent 5788c25 commit 869e957

File tree

1 file changed

+16
-1
lines changed

1 file changed

+16
-1
lines changed

list/list.mbt

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1199,7 +1199,22 @@ pub fn[A] iter2(self : T[A]) -> Iter2[Int, A] {
11991199
/// Convert the iterator into a list. Preserves order of elements.
12001200
/// If the order of elements is not important, use `from_iter_rev` instead.
12011201
pub fn[A] from_iter(iter : Iter[A]) -> T[A] {
1202-
iter.fold(init=Empty, fn(acc, e) { More(e, tail=acc) }).reverse_inplace()
1202+
let mut res = Empty
1203+
let mut ptr = Empty
1204+
for x in iter {
1205+
match (res, ptr) {
1206+
(Empty, _) => {
1207+
res = More(x, tail=Empty)
1208+
ptr = res
1209+
}
1210+
(More(_), More(_) as ptr_) => {
1211+
ptr_.tail = More(x, tail=Empty)
1212+
ptr = ptr_.tail
1213+
}
1214+
(_, _) => abort("unreachable")
1215+
}
1216+
}
1217+
res
12031218
}
12041219
12051220
///|

0 commit comments

Comments
 (0)