Looks like push! reduces memory allocation by a constant-ish factor of 
10^3, but reduces execution time exponentially. push!ing 10000 elements 
takes the same time as copying 10. (gist 
<https://gist.github.com/stillyslalom/e8a5ad6bc93928ef2109>)


<https://lh3.googleusercontent.com/-sn3choQLcDU/VkkW6DuOJ6I/AAAAAAAAE3I/05Gkn9Vya1c/s1600/push_v_copy.png>

<https://lh3.googleusercontent.com/-hfdVlOGr8RI/VkkW8IYVcwI/AAAAAAAAE3Q/tMc0AK6tQYg/s1600/push_v_copy_malloc.png>


On Sunday, November 15, 2015 at 3:42:18 AM UTC-6, Dan wrote:
>
> AFAIK the implementation of `push!` in Julia only occasionally allocates a 
> bigger buffer for the new vector. This results in a very low average time 
> for adding multiple elements (O(1) amortized time in complexity jargon).
>
> Notice, `a = [a new_element ]` would in Julia do something else than 
> `push!` - it would create a new array (with allocation), put the old `a` 
> and `new_element` in it, and then rebind the symbol `a` to the new array, 
> and let the garbage collector free the old array. This would be costly, so 
> it's better to use push!.
>
> Even better, is to do the experiment and possibly report the answers on 
> the list with working code, timings and versions. Hope this helps.
>
> On Sunday, November 15, 2015 at 6:51:30 AM UTC+2, Achu wrote:
>>
>> So in Matlab there's a pretty big difference in performance between 
>> preallocating an array, and growing it in a loop with a=[a new_element];
>> How big is the performance difference in Julia between preallocating and 
>> using push! to grow the array in a loop?
>>
>> Thanks!
>> Achu
>>
>

Reply via email to