性能分析|青训营笔记

43 阅读2分钟

day2

高质量编程

  • 高质量:正确可高,简洁清晰

    • 边界条件
    • 健壮性
    • 可读性
  • 代码规范

    • 代码格式

    • 注释

      • 解释代码作用
      // Open opens the named file for reading. If successful, methods onthe returned file can be used for reading; the associated file
      // descriptor has mode O RDONLY.
      // If there is an error, it will be of type xPathError
      func Open(name string) (*File, error) {return OpenFile(name,0 RDONLY,0){
      }
      
      • 原因

      • 思路

        // Process every element in the listfor 
        e := rangeelements {process(e)
        
      • 为何出错

      // parseTimeZone parses a time zone string and returns its length, Time zones// are human-generated and unpredictable. We can't do precise error checking1/ On the other hand, for a correct parse there must be a time zone at the
      // beginning of the string, so it's almost always true that there's one
      // there. We look at the beginning of the string for a run of upper-case letters.
      // If there are more than 5,it's an error.
      // If there are 4 or 5 and the last is a T,it's a time zone
      // If there are 3,it's a time zone.
      // Otherwise,other than special cases, it's not a time zone
      // GMT is special because it can have an hour offset.
      func parseTimeZone( value string) (length int, ok bool)
      
    • 命名规范

      • 缩写词全大写
      • 函数名不携带包名的上下文信息
      • 包只有小写字母组成,不要与标准库重名
    • 控制流程

    • 错误和异常处理

      • 简单的异常处理
      func defaultCheckRedirect(req *Request, via [ ]*Request) error {
          if len(via) >= 10 {
              return errors. New( "stopped after 10 redirects")
          }
          return nil
      }
      
      • 错误的 Wrap 和 Unwrap 错误的 Wrap 实际上是提供了一个 error 嵌套另一个error 的能力,从而生成一个 error 的跟踪链在 fmt.Errorf 中使用: % w 关键字来将一个错误关联至错误链中
      list,-, err := c.GetBytes(cache.Subkey(a.actionID,"srcfiles"))
      if err != nil {
          return fmt.Errorf("reading srcfiles list: %w", err)
      }
      
      • 错误判定:

        • 判定一个错误是否为特定错误,使用 errors.Is 不同于使用 -=,使用该方法可以判定错误链上的所有错误是否含有特定的错误
      data, err = lockedfile .Read( targ )
      if errors.Is(err, fs.ErrNotExist) {
          "latestn file
          // Treat non-existent as empty, to bootstrap the
          // the first time we connect to a given database
          return []bytef{}, nil
      return data, err
      

性能调优

  • 是综合评估,时间和空间效率有时候不可兼得
  • slice预分配内存

    • 尽可能在使用make()初始化切片时提供容量信息

image-20230117145344533

  • map 预分配

    • 向map中添加元素的操作会触发map的扩容
    • 提前分配好空间可以减少内存拷贝和Rehash的消耗
    • 建议根据实际需求提前预估好需要的空间
  • strings.Builder字符串处理

  • atomic包

    • 多线程,时间性能比加锁高

原则

  • 依靠数据
  • 定位最大瓶颈
  • 不要过早优化
  • 不要过度优化