title: Julia - Is there a way to avoid using a loop without using too much memory
body: <p>Consider the following example:</p>
  
  <pre><code>module structs
  mutable struct testStruct
      x::Array{Int64,2}
  end
  end
  
  function innerFunc(s::structs.testStruct)
      s.x[1:2] .= s.x[3:4]
  end
  
  function structTest!(s::structs.testStruct, n)
      for i = 1:n
          innerFunc(s)
      end
      println(s.x)
  end
  </code></pre>
  
  <p>The memory allocations, as I increase <code>n</code>, increase as well. I think that's because in each iteration, I'm creating an allocation for <code>s.x[3:4]</code>. I can avoid this by using a loop:</p>
  
  <pre><code>function innerFunc(s::structs.testStruct)
      for i = 1:2
          s.x[i] .= s.x[i+2]
      end
  end
  
  function structTest!(s::structs.testStruct, n)
      for i = 1:n
          innerFunc(s)
      end
      println(s.x)
  end
  </code></pre>
  
  <p>However, I don't like loops because the syntax is burdensome. Is there a way to avoid it? In each iteration, I want to modify the first and second elements of <code>s.x</code> without increasing memory allocations as I increase <code>n</code> since I'm not creating anything new.</p>
  
  <p><strong>UPDATE: In response to DNF, I tried to use <code>@view</code>:</strong></p>
  
  <pre><code>module structs
  mutable struct testStruct
      x::Array{Int64,2}
  end
  end
  
  function innerfunc!(s::structs.testStruct)
      s.x[1:2] .= view(s.x, 3:4)
  end
  
  function structTest!(s::structs.testStruct, n)
      for i = 1:n
          innerfunc!(s)
      end
      println(s.x)
  end
  </code></pre>
  
  <p>This is what I got:</p>
  
  <pre><code>@time structTest!(structs.testStruct([1 2 3 4]),33)
  0.000112 seconds (202 allocations: 7.938 KiB)
  
  @time structTest!(structs.testStruct([1 2 3 4]),330)
  0.000126 seconds (1.69 k allocations: 68.266 KiB)
  </code></pre>
  
  <p>I want the allocations to stay invariant to <code>n</code>.</p>