Crystal: Sub-array iterateration without clone to new array

Created on 5 Oct 2016  路  3Comments  路  Source: crystal-lang/crystal

Both array[start, count].each and array[range].each makes a new array (losing time and memory in allocation) and the closest way I've found is iterating through indices and accessing with array[i]

(start...stop).each do |i|
  value = array[i]
  # do something with `value`
end

but iterating through indices, when I want values, loses Ruby-style iteration.

Is this intentional? (maybe to avoid data-race?)

I didn't make a direct PR because I don't know if should it be in Array(T) or Indexable(T) and which are the best method names(or overloads). eg.:

  • #each(*, start : Int, stop : Int)
  • #each(*, within : Range(Int, Int))
  • #each_within(range : Range(Int, Int))

What do you think?

draft stdlib

Most helpful comment

I actually needed this a few times and it also bothered me to go back to index iteration and then accessing the array.

So yes, having something like what you propose would be really nice, it could be applied generally to any Indexable.

All 3 comments

I actually needed this a few times and it also bothered me to go back to index iteration and then accessing the array.

So yes, having something like what you propose would be really nice, it could be applied generally to any Indexable.

I somehow believed it should be done in compile-time optimization.
In script-like languages, I assume the compiler does all clever jobs, and I stay foolish 馃槃

@chaniks even assuming a perfect optimiser the compiler wouldn't be able to optimise this without changing the behaviour of the program because duplicating then iterating has a different behaviour to simply iterating when the array is being modified from another thread.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

lgphp picture lgphp  路  3Comments

jhass picture jhass  路  3Comments

costajob picture costajob  路  3Comments

will picture will  路  3Comments

oprypin picture oprypin  路  3Comments