Overriding iteration
Steven Schveighoffer
schveiguy at yahoo.com
Fri Mar 4 10:27:19 PST 2011
On Fri, 04 Mar 2011 12:13:34 -0500, spir <denis.spir at gmail.com> wrote:
> On 03/04/2011 05:43 PM, Steven Schveighoffer wrote:
>> But with the current compiler, you can use opApply to achieve that
>> behavior.
>
> opApply should work but it is supposed to be slower.
It depends on the application and aggregate you are trying to iterate.
If inlining is possible, ranges can be extremely fast. However, there are
certain applications that are better suited or only work with opApply:
* iterating polymorphic types (i.e. classes or interfaces)
* iterating non-linearly (e.g. iterating a tree)
* iterating multiple items in foreach (i.e. foreach(i, v; arr) )
In addition, LDC is able to inline opApply delegates that are
compiler-generated, making opApply pretty much as fast as a range
iteration. I hope some day dmd can do this too.
> Defining range primitives directly on the object/container cannot work
> as of now, unfortunately, because of a pair of bugs (conflicts in
> formatValue template definitions between struct/class on one hand and
> ranges on the other).
It is not a good idea to define range primitives on a container. This
would mean that iterating the container destroys the data. What you want
is a range on the container, and to iterate that range. Think of a range
as a view of the data in the container. Think of the container as the
owner of the data. A confusing aspect is that builtin arrays are often
thought of as containers. They are not containers, they are ranges. The
owner of the data is actually the GC.
-Steve
More information about the Digitalmars-d-learn
mailing list