rust - Is it always preferable to populate a reference vs moving an owned value? -
coming rust dynamic languages python, i'm not used programming pattern provide function mutable reference empty data structure , function populates it. typical example reading file string
:
let mut f = file::open("file.txt").unwrap(); let mut contents = string::new(); f.read_to_string(&mut contents).unwrap();
to python-accustomed eyes, api create owned value within function , move out return value looks more intuitive / ergonomic / have you:
let mut f = file::open("file.txt").unwrap(); let contents = f.read_to_string().unwrap();
since rust standard library takes former road, figure there must reason that.
is preferable use reference pattern? if so, why? (performance reasons? specifically?) if not, how spot cases might beneficial? useful when want return value in addition populating result data structure (as in first example above, .read_to_string()
returns number of bytes read)? why not use tuple? matter of personal preference?
if read_to_string
wanted return owned string
, means have heap allocate new string
every time called. also, because read
implementations don't know how data there read, have incrementally re-allocate work-in-progress string
multiple times. means every temporary string
has go allocator destroyed.
this wasteful. rust system programming language. system programming languages abhor waste.
instead, caller responsible allocating , providing buffer. if call read_to_string
once, nothing changes. if call more once, however, can re-use same buffer multiple times without constant allocate/resize/deallocate cycle. although doesn't apply in specific case, similar interfaces can design support stack buffers, meaning in cases can avoid heap activity entirely.
having caller pass buffer in strictly more flexible alternative.
Comments
Post a Comment