MST

星途 面试题库

面试题:Go语言switch语句针对非常量表达式的优化策略

在Go中,switch语句可以针对非常量表达式进行判断。当处理复杂的非常量表达式作为switch的判断条件时,从性能和代码可读性角度,你会采取哪些优化策略?请结合具体的业务场景举例说明。
31.8万 热度难度
编程语言Go

知识考点

AI 面试

面试题答案

一键面试
  1. 性能优化策略
    • 减少重复计算:如果非常量表达式计算成本较高,可提前计算并存储结果。例如,在处理图片处理业务场景中,可能需要根据图片的宽高比来执行不同操作。宽高比的计算可能涉及文件读取和解析,这是比较耗时的。
    package main
    
    import (
        "fmt"
    )
    
    func getAspectRatio(width, height int) float64 {
        return float64(width) / float64(height)
    }
    
    func main() {
        width := 800
        height := 600
        aspectRatio := getAspectRatio(width, height)
        switch {
        case aspectRatio > 1.5:
            fmt.Println("Wide - screen image, perform wide - screen specific processing")
        case aspectRatio < 0.8:
            fmt.Println("Tall - screen image, perform tall - screen specific processing")
        default:
            fmt.Println("Normal - aspect image, perform normal processing")
        }
    }
    
    • 使用查找表(map)替代复杂逻辑:当判断条件有固定的映射关系时,使用map来实现快速查找。比如在游戏开发中,根据不同的角色ID执行不同的技能逻辑。
    package main
    
    import (
        "fmt"
    )
    
    type CharacterID int
    const (
        WarriorID CharacterID = iota
        MageID
        RogueID
    )
    
    type SkillFunc func()
    var skillMap = map[CharacterID]SkillFunc{
        WarriorID: func() { fmt.Println("Warrior skill: Slash") },
        MageID: func() { fmt.Println("Mage skill: Fireball") },
        RogueID: func() { fmt.Println("Rogue skill: Stealth") },
    }
    
    func main() {
        characterID := WarriorID
        if skill, ok := skillMap[characterID]; ok {
            skill()
        } else {
            fmt.Println("Unknown character ID")
        }
    }
    
  2. 代码可读性优化策略
    • 抽取复杂表达式为函数:使switch语句更加简洁明了。在电商系统中,根据用户的购买历史和会员等级决定是否给予特殊折扣。
    package main
    
    import (
        "fmt"
    )
    
    type User struct {
        purchaseAmount float64
        memberLevel int
    }
    
    func shouldGiveSpecialDiscount(user User) bool {
        return user.purchaseAmount > 1000 && (user.memberLevel >= 3)
    }
    
    func main() {
        user := User{
            purchaseAmount: 1200,
            memberLevel: 4,
        }
        switch {
        case shouldGiveSpecialDiscount(user):
            fmt.Println("Give special discount")
        default:
            fmt.Println("No special discount")
        }
    }
    
    • 使用注释:对于复杂的判断逻辑,添加注释说明每个case分支的含义。例如在网络协议解析场景中,根据不同的协议字段组合执行不同的处理逻辑。
    package main
    
    import (
        "fmt"
    )
    
    type NetworkPacket struct {
        protocolVersion int
        flag1 bool
        flag2 bool
    }
    
    func main() {
        packet := NetworkPacket{
            protocolVersion: 2,
            flag1: true,
            flag2: false,
        }
        switch {
        case packet.protocolVersion == 2 && packet.flag1 &&!packet.flag2:
            // Handle version 2 with flag1 set and flag2 unset, for example, perform a specific handshake
            fmt.Println("Perform version 2 specific handshake")
        default:
            fmt.Println("Unknown packet configuration")
        }
    }