Very detailed explanation, thank you!

On Tuesday, May 10, 2016 at 11:35:43 PM UTC+3, Yichao Yu wrote:
>
> On Tue, May 10, 2016 at 4:24 PM, Andrei Zh <faithle...@gmail.com 
> <javascript:>> wrote: 
> > From performance perspective, how bad it is to use `push!(array, 
> element)` 
> > compared to pre-allocating array and setting elements in it? 
>
> If you know the size ahead of time, always pre allocate it. 
> Resizing the array reuse memory if possible and double the buffer 
> every time (until a relatively large threshold iirc) so the time 
> memory is reallocated is O(log(size of array)). 
>
> Cost of not pre-allocating comes from realloc cost (which is a small 
> constant factor more expensive than pre-allocating) and disabling some 
> optimizations (e.g. a `push!` loop can't (or very hard to) be 
> vectorized (SIMD)). Chances are if it's hard to know the size ahead of 
> time, the compiler doesn't have much room to optimize anyway and since 
> the realloc cost is not particularly high, you might as well use a 
> loop to append elements. 
>
> > 
> > More generally, how extending arrays works in Julia? (code in array.c is 
> > quite readable, but some high-level description is appreciated) 
>

Reply via email to