title: Why is string creation so slow in Julia?
body: <p>I'm maintaining a Julia library that contains a function to insert a new line after every 80 characters in a long string.</p>
  <p>This function becomes extremely slow (seconds or more) when the string becomes longer than 1 million characters. Time seems to increase more than linearly, maybe quadratic. I don't understand why. Can someone explain?</p>
  <p>This is some reproducible code:</p>
  <pre><code>function chop(s; nc=80)
      nr   = ceil(Int64, length(s)/nc)
      l(i) = 1+(nc*(i-1)) 
      r(i) = min(nc*i, length(s))
      rows = [String(s[l(i):r(i)]) for i in 1:nr]
      return join(rows,'\n')
  end
  
  s = &quot;A&quot;^500000
  
  chop(s)
  </code></pre>
  <p>It seems that this row is where most of the time is spent: <code>rows = [String(s[l(i):r(i)]) for i in 1:nr]</code></p>
  <p>Does that mean it takes long to initialize a new <code>String</code>? That wouldn't really explain the super-linear run time.</p>
  <p>I know the canonical fast way to build strings is to use <code>IOBuffer</code> or the higher-level <code>StringBuilders</code> package: <a href="https://github.com/davidanthoff/StringBuilders.jl" rel="noreferrer">https://github.com/davidanthoff/StringBuilders.jl</a></p>
  <p>Can someone help me understand why this code above is so slow nonetheless?</p>
  <p>Weirdly, the below is much faster, just by adding <code>s = collect(s)</code>:</p>
  <pre><code>function chop(s; nc=80)
      s = collect(s) #this line is new
      nr   = ceil(Int64, length(s)/nc)
      l(i) = 1+(nc*(i-1)) 
      r(i) = min(nc*i, length(s))
      rows = [String(s[l(i):r(i)]) for i in 1:nr]
      return join(rows,'\n')
  end
  </code></pre>