foreach - premature optimization vs cultivating good habits
Laeeth Isharc via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Fri Jan 30 06:41:10 PST 2015
On Friday, 30 January 2015 at 12:55:20 UTC, Adam D. Ruppe wrote:
> On Friday, 30 January 2015 at 11:55:16 UTC, Laeeth Isharc wrote:
>> As I understand it, foreach allocates when a simple C-style
>> for using an array index would not.
>
> foreach is just syntax sugar over a for loop. If there's any
> allocations, it is because your code had some, it isn't inherit
> to the loop. The doc definition even lists the translation of
> foreach to for in the case of ranges explicitly:
>
> http://dlang.org/statement.html#ForeachStatement
>
>
> The most likely allocation would be to a user-defined opApply
> delegate, and you can prevent that by making it opApply(scope
> your_delegate) - the scope word prevents any closure allocation.
Thanks, Adam. That's what I had thought (your first paragraph),
but something Ola on a different thread confused me and made me
think I didn't understand it, and I wanted to pin it down.
The second paragraph is very helpful - appreciate it.
Laeeth.
More information about the Digitalmars-d-learn
mailing list