英文:
How to make this code more performant?
问题
我有这样一段代码,它遍历一个映射并根据关系类型过滤一些字段,我必须运行两个循环,并且对于大型映射来说,我觉得速度会很慢。有没有什么方法/重构可以使这段代码更高效。
func getFields(filter map[string]map[string]bool, msg *Message) (fs []Field) {
for k, _ := range filter {
if relationString(msg) == k {
if fieldFilter, ok := filter[k]; ok {
for _, f := range msg.Fields {
if _, ok := fieldFilter[f.Name]; ok {
fs = append(fs, f)
}
}
}
}
}
return
}
英文:
I have this snippet of code that iterate over a map and filter some fields based on relation type, I have to run two loops and have a feeling that it is going to be slow for big maps. Is there any way I can technique/refactoring to make this code more performant.
func getFields(filter map[string]map[string]bool, msg *Message) (fs []Field) {
for k, _ := range filter {
if relationString(msg) == k {
if fieldFilter, ok := filter[k]; ok {
for _, f := range msg.Fields {
if _, ok := fieldFilter[f.Name]; ok {
fs = append(fs, f)
}
}
}
}
}
return
}
答案1
得分: 1
你不需要外部循环作为一种改进:
func getFields(filter map[string]map[string]bool, msg *Message) (fs []Field) {
if fieldFilter, ok := filter[relationString(msg)]; ok {
for _, f := range msg.Fields {
if _, ok := fieldFilter[f.Name]; ok {
fs = append(fs, f)
}
}
}
return
}
英文:
You don't need the outer loop as one improvement:
func getFields(filter map[string]map[string]bool, msg *Message) (fs []Field) {
if fieldFilter, ok := filter[relationString(msg)]; ok {
for _, f := range msg.Fields {
if _, ok := fieldFilter[f.Name]; ok {
fs = append(fs, f)
}
}
}
}
return
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论