How efficient are push!() and append!() methods in Julia?

前端 未结 2 1548
予麋鹿
予麋鹿 2021-01-01 16:57

On this page it says that methods push!() and append!() are very efficient.

My question is how exactly efficient they are?

Namely,<

2条回答
  •  春和景丽
    2021-01-01 17:28

    push! will always be slower than inserting into a pre-allocated array, if for no other reason than push! (1) inserts the element, just as when you do so manually, and (2) increments the length of the array. Two operations cannot be faster than one, when one is part of two.

    However, as noted in other answers the gap is often not so large as to something to be concerned about. Internally (last time I checked the code), Julia uses a grow-by-a-factor-of-2 strategy, so that you only need log2(N) reallocations.

    If you do know the size of the array in advance, you can eliminate reallocations by using sizehint!. As you can easily test for yourself, this does not eliminate the performance penalty relative to insertion into a preallocated array, but it can reduce it.

提交回复
热议问题