title: Netlogo efficiency: Asking neighbouring patches to loop through table and obtain value
body: <p>In my model, agents move and record a patch variable (weighted-index) for the patch they are on as well as all patches in-radius 16 into a table that is different for each turtle (representing memory). At each time step, I ask the surrounding patches of each turtle to set a patch variable (perceived-index) equal to the current patch variable (weighted-index) + the value for weighted-index that was stored in the table from the previous visit (memvalue). This is assuming that the turtle encountered a value for weighted-index and stored it in a table, returned later to that same patch (which now has a new value), and is using information for the current index amount and the remembered amount to decide whether it will move to that patch or not. My model becomes extremely slow when I add a foreach loop asking the surrounding patches to obtain the memvalue from the memory table. My world is pretty large but this code only deals with about 800 patches on the first tick and it still takes about 5 seconds per tick.</p>
  
  <pre><code>    ; Viewshed is a patch-set of the surrounding patches
      ; patch-memmap is the table containing food values from previous visits
      ; id is a single number used to identify patches (as opposed to using coordinates) 
  
    set viewshed (patches in-radius 16 with [AOI? = 1])
    let patch-memmap memory-map
    ask viewshed
    [
      ifelse Memory [
        foreach sort viewshed [ x -&gt;
      ask x [
            ifelse table:has-key? patch-memmap id
            [
              let memvalue table:get patch-memmap id
              set perceived-index ((((weighted-index * (exp (- distance me))) * 0.7) + (memvalue * 0.3)))
              ]
            [set perceived-index (weighted-index * (exp (- distance me)))]
    ]]
    ]
      [set perceived-index (weighted-index * (exp (- distance me)))]
    ]
  </code></pre>
  
  <p>The model works but I was hoping someone might have any ideas on how to do this differently to increase efficiency. Thank you all in advance for your help!</p>