Ranges require GC?
Jonathan M Davis
jmdavisProg at gmx.com
Tue Dec 10 18:37:12 PST 2013
On Wednesday, December 11, 2013 03:09:52 Frustrated wrote:
> But surely memory gets allocated in some way?
>
> In Programming in D:
>
> "For example filter(), which
> chooses elements that are greater than 10 in the following code,
> actually returns a range
> object, not an array:"
>
> But if filter is a range and returns an object then how is that
> object allocated?
It's on the stack. filter returns a struct whose only member is the range that
was passed to it. The lambda that you pass to filter might be allocated on the
heap under some circumstances, but that's the only risk of heap allocation
with filter, and if you use a function rather than a lambda literal or a
delegate, then you definitely don't get any heap allocation (and I don't think
that it's even the case that you necessarily get a heap allocation with a
lambda).
Most ranges in Phobos are very lightweight, because they just wrap another
range and maybe add a member variable or two to handle what they do (and many
don't even need that). And if the optimizer does a decent job, then most of
the wrappers even get optimized away, causing very little overhead at all
(though I'm sure that dmd can be improved in that regard).
Whether any particular range allocates anything on the heap depends on the
range, but it's likely to be very rare that they will - particularly in
Phobos.
- Jonathan M Davis
More information about the Digitalmars-d-learn
mailing list