logoalt Hacker News

edflsafoiewqyesterday at 11:44 PM3 repliesview on HN

Doesn't reduce force the accumulator to be shared though? Both the reduce and the lambda are holding onto references to acc, which defeats any "single reference" optimizations.


Replies

vhcrtoday at 3:14 AM

The problem with:

    ret = ""
    for s in strings:
        ret += s
is that it re-allocates O(n) times, even if ret is referenced only once.
show 1 reply
ndriscolltoday at 12:12 AM

  def reduce(acc, f): 
    for v in self:
      acc = f(acc, v)
    return acc
The current acc goes out of scope each time you call f. There's no shared reference (assuming f doesn't sneak store it elsewhere, which for string combining, f should just be `return a+b`?).
show 1 reply
Zaktoday at 12:18 AM

It might - let's assume it does. My point is that it's better to use the explicit optimized method for joining strings in a performance-sensitive context than to try to meet the conditions for an implicit optimization.