vlang / v

Simple, fast, safe, compiled language for developing maintainable software. Compiles itself in <1s with zero library dependencies. Supports automatic C => V translation. https://vlang.io
MIT License
35.5k stars 2.15k forks source link

Perf: arrays.sum #21710

Closed esquerbatua closed 1 week ago

esquerbatua commented 1 week ago

Remove the check inside the loop, initializing value with 0

spytheman commented 1 week ago

mut head := 0 will work only for integers, but not for other types like Structs etc, unlike mut head := array[0] .

spytheman commented 1 week ago

Try this for example:

import arrays

struct Abc {
    x int = 5
}

fn (a Abc) + (b Abc) Abc {
    return Abc{
        x: a.x + b.x
    }
}

a := [1, 2, 3, 5]
dump(arrays.sum(a)!)

s := [Abc{
    x: 30
}, Abc{
    x: 20
}, Abc{
    x: 10
}]
dump(arrays.sum(s)!)

printing:

[a.v:14] arrays.sum(a)!: 11
[a.v:23] arrays.sum(s)!: Abc{
    x: 60
}
esquerbatua commented 1 week ago

mut head := 0 will work only for integers, but not for other types like Structs etc, unlike mut head := array[0] .

Right, sorry, I'll think another solution to optimize it. Ty!

spytheman commented 6 days ago

if your goal is to just avoid the check with the continue, a C style for loop: for i:=1; i<a.len;i++ { e := a[i] ... can work, skipping the 0th element.