Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Perf: arrays.sum #21710

Closed
wants to merge 2 commits into from
Closed

Perf: arrays.sum #21710

wants to merge 2 commits into from

Conversation

esquerbatua
Copy link
Contributor

Remove the check inside the loop, initializing value with 0

Remove the check inside the loop, initializing value with 0
@spytheman
Copy link
Member

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

@spytheman
Copy link
Member

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
}

@spytheman spytheman closed this Jun 21, 2024
@esquerbatua
Copy link
Contributor Author

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
Copy link
Member

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

2 participants