Removing elements from dynamic arrays?
Siarhei Siamashka
siarhei.siamashka at gmail.com
Thu Apr 7 00:31:36 UTC 2022
On Wednesday, 6 April 2022 at 19:28:53 UTC, Steven Schveighoffer
wrote:
> With `arr.find!(someLambda)`, if the lambda is using data from
> outside the lambda, it needs a closure, which means it may
> (probably does) allocate your needed data into a GC heap block
> that will then become garbage after the function is gone.
>
> With `arr.find(value)`, it searches the array for something
> that compares with the value. No allocation happens, and it's
> equivalent to what you would write in a for loop.
>
> Especially for the code in question:
>
> ```d
> arr.find(val); // like a for loop, comparing each element to val
> arr.find!(v => v == val); // requires a context pointer for
> val, may allocate.
> ```
>
> There is no difference functionally -- both perform exactly the
> same task, but one is just more expensive.
There shouldn't be any significant difference in performance. A
good optimizing compiler is expected to ensure that
templates/lambdas are inlined here and no heap/GC allocation
happens. Unfortunately DMD is not an optimizing compiler and this
indeed may have some impact on the preferred coding style if
people really care about the performance of their code even when
it is compiled by DMD.
Lambdas and closures aren't even a unique feature of D language.
C++ supports them too and sets the bar for performance
expectations: https://www.elbeno.com/blog/?p=1068
Currently my own preferred performance test for the optimizing D
compiler quality would be this solution of
https://atcoder.jp/contests/abc230/tasks/abc230_e based on binary
search:
* https://atcoder.jp/contests/abc230/submissions/27673369 (D)
* https://atcoder.jp/contests/abc230/submissions/27743857 (C++)
* https://atcoder.jp/contests/abc230/submissions/27741770 (D with
gallopBackwards search policy as a bonus)
Using templates from Phobos as building blocks, chaining them
together via UFCS and using a lambda is expected to be roughly as
efficient as implementing an imperative binary search loop. If
this isn't the case, then there's a defect in the compiler to be
investigated and fixed.
More information about the Digitalmars-d-learn
mailing list