2

How efficient is typeof when dealing with complex expressions?

Specifically, in the two cases:

  • complex expressions that consist entirely of constant parts needing no CTFE to evaluate

  • complex expressions that need to mixin() a CTFE'ed string.

I don't know if it's fundamentally different but those are the two cases that concern me.

Mat
  • 202,337
  • 40
  • 393
  • 406
Noein
  • 522
  • 1
  • 6
  • 16
  • 1
    If the result is a struct, it's evaluated in compile time. I'm not sure what happens if classes and polymorphism is involved. I guess it is either evaluated in compile time, or in case of ambiguity it boils down into a simple lookup in the d-runtime. In short it's efficient. – Tamas Sep 06 '15 at 07:32
  • @Tamas : I believe it's all CT no matter the polymorphism situation (it just returns the lowest base class). RT polymorphism uses `typeid` instead. My concern is with how typeof deals with expressions that may need CTFE or rely on other multiple-path compile-time reflection algorithm (using `__traits` for example). _All would still be a CT action_, but I'm wondering how efficient that is at compile time. – Noein Sep 06 '15 at 11:49
  • 2
    `typeof` doesn't evaluate its argument; there wouldn't be any CTFE or mixin statements to evaluate unless the expression uses a template which uses them. – Colonel Thirty Two Sep 06 '15 at 19:16

1 Answers1

4

It depends, if you are interest in run time efficiency or compile time efficiency. typeof(expr) has zero run time overhead it is completly evaluated at compile time.

Compile time complexity is a quite low, so you generaly does not need to worried about it.

Kozzi11
  • 2,413
  • 12
  • 17
  • I'm aware it is entirely a compile time action ('cause D is statically typed). But D also has `mixin`s among other complicated CT-reflection tools. My Q: Do those get `typeof` results in more time or cause non-mixin expressions to also be slower to typeof to account for the increased complexity due to mixins/CT-reflected-generated-code? – Noein Sep 06 '15 at 11:44
  • 1
    Only if a mixin expression actually occurs in the typeof does it need to be evaluated.... then it can be as slow as that is, but otherwise the types are all known. Even like typeof(func()) where func returns auto is easy to calculate most the time - it just looks at the type of the first return statement (which is probably already known and cached, unless this is the very first time it is instantiated), which is easy. typeof(a+b) looks up the field on a and b, then gets the common type of them which is a short if/else series. So pretty fast. only mixin(str) really can slow down. – Adam D. Ruppe Sep 06 '15 at 12:41
  • And then again strings are just arrays and will be processed pretty quickly. – Bauss Sep 07 '15 at 05:54