File tree Expand file tree Collapse file tree 1 file changed +7
-5
lines changed Expand file tree Collapse file tree 1 file changed +7
-5
lines changed Original file line number Diff line number Diff line change @@ -743,8 +743,8 @@ impl<T: TypeNum> PyArray<T, Ix1> {
743
743
/// Construct one-dimension PyArray from a type which implements
744
744
/// [`IntoIterator`](https://doc.rust-lang.org/std/iter/trait.IntoIterator.html).
745
745
///
746
- /// This method can allocate memory multiple times and not fast.
747
- /// When you can use [from_exact_iter](method.from_exact_iter.html), we recommend to use it .
746
+ /// If no reliable [`size_hint`](https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.size_hint) is available,
747
+ /// this method can allocate memory multiple time, which can hurt performance .
748
748
///
749
749
/// # Example
750
750
/// ```
@@ -758,13 +758,15 @@ impl<T: TypeNum> PyArray<T, Ix1> {
758
758
/// # }
759
759
/// ```
760
760
pub fn from_iter ( py : Python < ' _ > , iter : impl IntoIterator < Item = T > ) -> & Self {
761
- let mut capacity = 512 / mem:: size_of :: < T > ( ) ;
761
+ let iter = iter. into_iter ( ) ;
762
+ let ( min_len, max_len) = iter. size_hint ( ) ;
763
+ let mut capacity = max_len. unwrap_or ( min_len. max ( 512 / mem:: size_of :: < T > ( ) ) ) ;
762
764
let array = Self :: new ( py, [ capacity] , false ) ;
763
765
let mut length = 0 ;
764
766
unsafe {
765
- for ( i, item) in iter. into_iter ( ) . enumerate ( ) {
767
+ for ( i, item) in iter. enumerate ( ) {
766
768
length += 1 ;
767
- if length >= capacity {
769
+ if length > capacity {
768
770
capacity *= 2 ;
769
771
array
770
772
. resize ( capacity)
You can’t perform that action at this time.
0 commit comments