map question
Siarhei Siamashka
siarhei.siamashka at gmail.com
Sun Jan 23 09:38:57 UTC 2022
On Sunday, 23 January 2022 at 09:08:46 UTC, Stanislav Blinov
wrote:
> Using `iota` here incurs additional computation and argument
> copies that are actually never used, i.e. wasted work. So I'd
> say go with `generate`, as that seems the intent.
Isn't this normally a compiler's job to eliminate all unused
computations and copies?
```D
auto foobar1(size_t n)
{
return n.iota.map!(_ => 123).array;
}
auto foobar2(size_t n)
{
return generate!(() => 123).take(n).array;
}
```
LDC with "-O -release" command line options generates pretty much
identical code for foobar1 and foobar2 (I'm only showing the main
loop, but the rest is also the same):
```
20: 48 39 c8 cmp %rcx,%rax
23: 74 18 je 3d
<_D2zz7foobar1FNaNbNfmZAi+0x3d>
25: c7 04 8a 7b 00 00 00 movl $0x7b,(%rdx,%rcx,4)
2c: 48 83 c1 01 add $0x1,%rcx
30: 48 39 cb cmp %rcx,%rbx
33: 75 eb jne 20
<_D2zz7foobar1FNaNbNfmZAi+0x20>
```
```
20: 48 39 c8 cmp %rcx,%rax
23: 74 18 je 3d
<_D2zz7foobar2FNaNbNfmZAi+0x3d>
25: c7 04 8a 7b 00 00 00 movl $0x7b,(%rdx,%rcx,4)
2c: 48 83 c1 01 add $0x1,%rcx
30: 48 39 cb cmp %rcx,%rbx
33: 75 eb jne 20
<_D2zz7foobar2FNaNbNfmZAi+0x20>
```
Do you have a better example to demonstrate `generate`'s
superiority?
More information about the Digitalmars-d-learn
mailing list