Missing introspection? "How exactly this type is actually used"

H. S. Teoh hsteoh at quickfur.ath.cx
Fri May 20 19:41:15 UTC 2022


On Fri, May 20, 2022 at 12:19:25PM -0700, Ali Çehreli via Digitalmars-d wrote:
> On 5/20/22 11:31, Adam D Ruppe wrote:
[...]
> > What's your goal here? To minimize the memory used at runtime?
> 
> Nothing is important really. My thought process was the following:
> 
> DbI allows range algorithms to e.g. provide random access:
> 
>   iota(10)
>     .map!(i => i)
>     .take(3)[1];
> 
> iota is uneful enough to provide opIndex, which is propagated by map
> and take and that random access works.
> 
> What if say, map used some expensive members (imagine some range type
> keeps an int[1000] for some reason) just because iota was
> isRandomAccessRange etc.  (Same for take.) If the user never had any
> interest for that machinery (for this particular use) then there would
> be both compile-time and runtime cost.

Actually, there would not be any compile-time or runtime cost if the
user doesn't actually use a method that requires calling the expensive
member.  For example, if opIndex for whatever reason is expensive
(though technically it should not be; it's supposed to be O(1) according
to the range API, IIRC), then .map would declare an opIndex that calls
this expensive method.  But if the user never calls map.opIndex, then
the template is never instantiated; the compiler wouldn't even process
the function body and no code is emitted for it in the executable.
That's the beauty of templated methods.

Of course, it's a different story if .map's implementation for whatever
reason uses DbI to determine that since .opIndex is present, we'll
always use it.  *Then* you'd be using the expensive method even if you
didn't intentionally call something that might require it.


> That's when I realized that there is no way of cutting that cost other
> than the user explicitly saying something like justInputRangePlease
> and it would be more efficient:
[...]

I'm pretty sure Phobos has a wrapper function that "hides" away higher
level methods in a range, like force something into an input range only
even if it's a forward range or higher. Maybe one of the unittesting
utility functions?  Or maybe I saw it once in a unittest.  I'm almost
certain Phobos has such a thing.  If it's not a public function, it'd be
a good idea to expose it as such.


T

-- 
Dogs have owners ... cats have staff. -- Krista Casada


More information about the Digitalmars-d mailing list