How to iterate over a tuple in Nim?
Asked Answered
I

2

12

Let's say I have a procedure getTuple(): (int, int, int). How do I iterate over the returned tuple? It doesn't look like items is defined for tuple, so I can't do for i in getTuple().

I initially had this returning a sequence, which proved to be a bottleneck. Can I get this to work without affecting performance? I guess as a last resort I could unroll my loop, but is there any way around that?

Ignaz answered 13/2, 2018 at 8:44 Comment(0)
P
3

I initially had this returning a sequence, which proved to be a bottleneck. Can I get this to work without affecting performance?

Use an array[N, int] instead, it has no indirection. Why was the seq not performant enough? You might want to allocate it to correct size with newSeq[int](size) initially.

Pooka answered 13/2, 2018 at 9:25 Comment(2)
My sequence was allocated correctly, but profiling showed lots of time spent calling newSeq. This was in the innermost loop of some performance-critical simulation code. I just tested array[N, int] and it's vastly superior - Thanks!Ignaz
Of course in an inner loop you wouldn't want to allocate seqs. Instead of copying the resulting array you could also pass in a pointer and write to the correct location directly.Pooka
I
11

OK, I figured this out. You can iterate over the tuple's fields:

let t = (2,4,6)

for x in t.fields:
  echo(x)
Ignaz answered 13/2, 2018 at 9:19 Comment(0)
P
3

I initially had this returning a sequence, which proved to be a bottleneck. Can I get this to work without affecting performance?

Use an array[N, int] instead, it has no indirection. Why was the seq not performant enough? You might want to allocate it to correct size with newSeq[int](size) initially.

Pooka answered 13/2, 2018 at 9:25 Comment(2)
My sequence was allocated correctly, but profiling showed lots of time spent calling newSeq. This was in the innermost loop of some performance-critical simulation code. I just tested array[N, int] and it's vastly superior - Thanks!Ignaz
Of course in an inner loop you wouldn't want to allocate seqs. Instead of copying the resulting array you could also pass in a pointer and write to the correct location directly.Pooka

© 2022 - 2024 — McMap. All rights reserved.