Element-wise operations and allocation

95 views
Skip to first unread message

Carlos Becker

unread,
Mar 10, 2014, 8:24:20 AM3/10/14
to julia...@googlegroups.com
Hello, I recently found out this:

julia>  b = rand((1024,1024))

julia>  sizeof(b)
8388608

julia>  @time b += 2;
elapsed time: 0.007002567 seconds (8388704 bytes allocated)


which, with further investigation, I could verify that it is allocating a new array every time I do something like b += 2,
instead of modifying the original object b points to.

Is this an intended behavior, or better, is there a command to optimize such operations?
I tried @devec but it also seems to generate a new destination array. I could also write my own function,
but I suppose there are better ways to deal with this.

Code such as b ./= 2 is very common, and this introduces array duplication, increasing memory usage as well as
additional unneeded operations (the former crashed my machine a few hours ago).

Thanks.

Cristóvão Duarte Sousa

unread,
Mar 10, 2014, 8:50:13 AM3/10/14
to julia...@googlegroups.com

Andreas Noack Jensen

unread,
Mar 10, 2014, 8:50:17 AM3/10/14
to julia...@googlegroups.com
When b is an array there will be a reallocation when doing *= or /=. Instead you can use scale!(c,2) for *=. For + you can use broadcast!(+,A,[2]). Maybe there should be a broadcast(Function,Array,Number) method.

If you update julia you'll also notice that A+=2 throws a deprecation warning because in the future you'll have to use .+ and .- for broadcasting. *= ad /= will still work for matrices.
--
Med venlig hilsen

Andreas Noack Jensen

Tim Holy

unread,
Mar 10, 2014, 9:07:40 AM3/10/14
to julia...@googlegroups.com
I'm heading out the door and don't have time to search for previous
discussions, but this has come up many times in the past---there are good (if
admittedly unfortunate) reasons for this. Someone needs to add this to the
FAQ!

--Tim
Reply all
Reply to author
Forward
0 new messages