Replies: 4 comments
-
It seems there is no way to avoid copying without adding Can we distinguish following 4 patterns, and separate behaviors?
With syntax highlighting (just in case table is difficult to read). for mut org in &orgs { // typeof(org) == mut &Org : `org` is mutable, and changing `org` will change `orgs` (data of `org` is address of current item in `orgs`) for mut org in orgs { // typeof(org) == mut Org : `org` is mutable, but changing `org` will not change `orgs` (data of `orgs` is copied to `org` for each iteration) for org in &orgs { // typeof(org) == &Org : `org` is immutable (data of `org` is address of current item in `orgs`) for org in orgs { // // typeof(org) == Org : `org` is immutable (data of `orgs` is copied to `org` for each iteration) |
Beta Was this translation helpful? Give feedback.
-
I'm not performance specialist though, With
Without
The code is following import benchmark
const (
max_iter = 1000 // 10000
)
struct LargeStruct {
mut:
thing [100000]u64
}
fn main() {
mut arr := []LargeStruct{len: 5}
mut out := LargeStruct{}
{
mut bmark := benchmark.start()
for _ in 0 .. max_iter {
for inst in &arr {
// (&LargeStruct(voidptr(unsafe {&inst}))).thing[0] = 1
mut inst_ := &LargeStruct(voidptr(unsafe { &inst }))
for i, _ in inst.thing {
inst_.thing[i] = u64(i)
out.thing[i] = inst_.thing[i]
}
}
}
bmark.measure('copy data [for $max_iter iter]')
}
{
mut bmark := benchmark.start()
for _ in 0 .. max_iter {
for mut inst in &arr {
mut inst_ := &LargeStruct(voidptr(unsafe { &inst }))
for i, _ in inst.thing {
inst_.thing[i] = u64(i)
out.thing[i] = inst_.thing[i]
}
}
}
bmark.measure('copy address [for $max_iter iter]')
}
mut res := u64(0)
for mut inst in &arr {
for val in inst.thing {
res += val
}
}
println(res)
} |
Beta Was this translation helpful? Give feedback.
-
All of these do slightly different things, and I am not sure what exactly is your question/observation. |
Beta Was this translation helpful? Give feedback.
-
What exactly do you want to achieve? |
Beta Was this translation helpful? Give feedback.
-
V version: V 0.3.0 02a47f4.70de4e1
OS: macos, macOS, 12.5.1, 21G83
What did you do?
What did you expect to see?
What did you see instead?
NOTE
My expectation for "
for
loop" is as follows.I expect
org
to be type of&Org
. (works as expected)I expect
org
to be type of&Org
. (🚨 NOT WORK)I expect
org
to be type ofOrg
,with warning of unnecessary(?) copy.
Beta Was this translation helpful? Give feedback.
All reactions