3 ms·
> those .replace() calls will allocate unnecessarily, All the time or only in Rust or Lisp? I would guess the compiler can optimize it because it is an XValue.
by kenniskrag 5y ago
> those .replace() calls will allocate unnecessarily,
All the time or only in Rust or Lisp? I would guess the compiler can optimize it because it is an XValue.
- mastax 5y ago`str::replace(from, to)` replaces all instances of the pattern `from` in the string with `to` returning the result as a newly allocated String. In theory the compiler could notice that the spaces added to the newly allocated strings are only used to influence the behavior of `split_whitespace` and do not otherwise affect the output of the function. In practice, it does not: https://rust.godbolt.org/z/z573Mvjzz https://rust.godbolt.org/z/z573Mvjzz The compiler does not decide to inline the call to `replace` and therefore does not do any special reasoning about it.
- lmkg 5y agoThose replace calls are growing the strings--one character is being replaced by several. That has the potential for re-allocation in any language, depending on how much spare space is present. Unless the optimizer is smart enough to figure out the space characters are never used because they're splitting points.