duan198811 2018-01-02 19:12
浏览 14

捕获数组索引错误

I'm just starting to learn Go, and I implemented an algorithm that checks four consecutive array indexes for an equal value in both diagonal directions, vertical, and horizontal. I designed it so that there is a function for each direction, and I'm wondering if there is a way for me to catch index errors without having to do the overhead to check if each index is in the range of index constraints.

func (state *State) checkTopLeftDiagonal(row, col int) bool {
    token := state.Board[row][col]
    b := token == state.Board[row-3][col-3] && token == state.Board[row-2][col-2] 
                  && token == state.Board[row-1][col-1]
    return b
}

func (state *State) CheckWinner(row, col int) bool {
    for i := 0; i < 4; i++ {
        if state.checkTopLeftDiagonal(row+i, col+i) == true {
            return true
        }
    }
    return false
}
  • 写回答

1条回答 默认 最新

  • dtl85148 2018-01-03 22:07
    关注

    What overhead?

    "Heavy" and "slow" programs generally work with tens or hundreds of thousands of data points every second. A single if statement quite literally takes a handful of clock cycles out of the billions of clock cycles that your computer goes through every second (1 GHz = 1 billion clock cycles on a single core machine).

    If you're worried about bounds checking overhead for (what seems to be) a fairly straightforward program, you shouldn't use Go. You shouldn't even use C++ or C. You should be writing this program directly in assembly and should spend hours fine-tuning each instruction to optimize on the scale of fractions of a nanosecond.

    Like @leafbebop stated in the comments, any other pattern will carry significantly more overhead.


    More generally, unless you go into a situation knowing the need for exceptionally high performance and low latency (such as electronic stock trading systems, gaming, or 3D rendering), it's usually better to build first and optimize later after you have "profiled" your code to identify the heavy parts. And unless your function is called millions of times a second, the amount of compute power that it'll use is virtually zero. What makes code slow is iterating over very large data sets, being bottlenecked waiting for the network (if processing thousands of network requests), or using large amounts of memory (in the range of gigabytes).

    An if statement does not make a program slow.

    Buying faster hardware is almost always cheaper than buying faster software (with more development time). :)

    评论

报告相同问题?

悬赏问题

  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据