-
Notifications
You must be signed in to change notification settings - Fork 42
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
Consider i++
as an assignment used in the iteration
#93
Comments
i++
as an assignment used in the iteration
Thanks for the issue! Similar questions have been adressed in f.ex. #81. I think I've never considered this since I think it's a bad pattern to use that kind of indexing. There are two linked posts about benchmarking assigning indexes vs appending if you set both a length and capacity of your slice in #81, please give those a read! Basically, I would suggest just writing this: func sortedKeys(m map[string]interface{}) sort.StringSlice {
keys := make(sort.StringSlice, 0, len(m))
for k := range m {
keys = append(keys, k)
}
sort.Sort(keys)
return keys
} It's not exactly a response to your question though since it's not the same code. If I didn't have any alternative but to use func sortedKeys(m map[string]interface{}) sort.StringSlice {
keys := make(sort.StringSlice, len(m))
i := 0
for k := range m {
keys[i] = k
i++
}
sort.Sort(keys)
return keys
} Or personally I would've grouped them in a var block for alignment: func sortedKeys(m map[string]interface{}) sort.StringSlice {
var (
keys = make(sort.StringSlice, len(m))
i = 0
)
for k := range m {
keys[i] = k
i++
}
sort.Sort(keys)
return keys
} If none of these alternatives feels relevant for you I think the other valid proposal would be #24 where the idea is to allow anything cuddled to any block as long as it's used in the block itself. This is a quite common patterns for channels and go routines or like in your case keeping track of a counter in a loop. |
It's incredible!
The version with |
My Bad. My old laptop CPU was heating and then reducing the CPU frequency. As that may provide biased results, I have changed the benchmark order. Multiple runs show
|
Thanks for taking the time to do new benchmarks. I guess this tells us that it's fine to use Also, the times we're talking about is extremely low, a diff of ~100 ns/op (if even that). This would only have any actual effect on very large numbers and big lists. For a list of 1000 items the added time would be 0.1 ms. |
Closing this since it's mostly sorted and would be resolved if we land #24 |
My original function:
I have found three possible fixes:
Isolate
i := 0
but this is the index of thefor
loopInverse both assignments
i := 0
andkeys := ..
but this is wired :-/Putting both assignments in one line, but this is the least readable :-(
I thing
wsl
should consideri++
as an assignment used in the iteration.@bombsimon What about your opinion?
The text was updated successfully, but these errors were encountered: