Open anzhi0708 opened 1 year ago
I noticed that de-optimization changes the behavior with for!
.
for_! = for!
arr = ![]
for_! 0..<5, i =>
arr.push!(() -> i)
for! arr, f =>
print! f, f()
<function <lambda> at 0x000001E1B8A3C720> 0
<function <lambda> at 0x000001E1B8B68540> 1
<function <lambda> at 0x000001E1B8B68680> 2
<function <lambda> at 0x000001E1B8B8B060> 3
<function <lambda> at 0x000001E1B8B8B100> 4
De-optimized, pure procedure for!
is defined here.
This is what we wanted, but de-optimized version is much slower.
# iteration with 0..<1000000
❯ hyperfine "cargo r test.er" # optimized (normal) version
Benchmark 1: cargo r test.er
Time (mean ± σ): 1.981 s ± 0.016 s [User: 1.493 s, System: 0.158 s]
Range (min … max): 1.964 s … 2.014 s 10 runs
❯ hyperfine "cargo r test.er" # de-optimized version
Benchmark 1: cargo r test.er
Time (mean ± σ): 3.168 s ± 0.120 s [User: 2.562 s, System: 0.255 s]
Range (min … max): 3.088 s … 3.475 s 10 runs
I will try to see if we can get the desired behavior without performance penalty.
Thanks for your reply! This is what I was looking for :-)
In this code snippet, the scope of the iteration variable i is global, and the anonymous function captures the variable by reference instead of by value during each iteration, which is consistent with Python but different from functional languages such as OCaml and Scala. To some extent, this behavior goes against intuition.
Output:
Scala 3
Output of Scala