Unexpected inefficiency of minIndex

Alexibu alex at sunopti.com
Fri Mar 22 07:18:01 UTC 2024


```d
import std.stdio;
import std.algorithm;

int potentiallyExpensiveCalculation(int arg)
{
	writefln("eval %s",arg);
	return arg;
}

int[] args = [1,2,3,-1,2];
auto best = args.map!(a => 
potentiallyExpensiveCalculation(a)).minIndex;
```
This needs n-1 compares, but is also computing 
potentiallyExpensiveCalculation twice as many times as necessary.

Why does map not fully resolve to the results before it is passed 
to minIndex, so that two ints are compared not two 
potentiallyExpensiveCalculation of ints.

I didn't know map was lazy...
I could put .array between map and minIndex but that defeats the 
purpose of ranges.


More information about the Digitalmars-d-learn mailing list