Why function template 'among' is of complexity O(1) and not O(n)?

anonymous anonymous at example.com
Wed Feb 19 16:36:38 PST 2014


On Wednesday, 19 February 2014 at 22:46:45 UTC, Chris Williams
wrote:
> When the template writes out the definition of the function, if 
> the parameters can be interpreted during compile-time, then the 
> foreach ( O(n) ) will be run by the compiler to detect the 
> correct parameter and the function will be written out as just 
> as a return statement in the body, without the loop. So during 
> runtime, the function would have an O(1) runtime.

That's an optimization the compiler may do, but it's not
guaranteed. And `among` is not special in this regard.

[...]
> The version which accepts three parameters will always run the 
> same speed no matter what you call it - since it does the same 
> thing exactly three times.

Well, it returns as soon as the value is found. So among(v, "b",
"c") finishes quicker when v is "b" than when it's "c" or "a". It
only does the same thing three times when it didn't find the
value after two times.


More information about the Digitalmars-d-learn mailing list