drbz99867 2017-12-12 22:56
浏览 3562

Golang在int和uint之间进行转换的成本

I'm porting some old C++ code to go which used unsigned integers fairly often. I can understand their use in the C++ to help ensure positive values were only used in certain places.

However I believe there was also some implicit type conversion going on so in the go version I've ended up with code which looks like

Node{IsTerminal: true, TerminalNo: uint(RandPostiveIntUpTo(int(fitnessCases.Terminals)))})

Which seems a little unnecessary. I'm curious, is there much of a (time) cost to this casting, and am I losing any significant safety by switching to use int everywhere?

  • 写回答

1条回答 默认 最新

  • dongqu3623 2017-12-13 02:29
    关注

    This code:

    package main
    
    import (
        "fmt"
        "time"
    )
    
    func main() {
        start := time.Now()
        var test uint = 3
        var tmp int
        for i := 0; i < 1000000000; i++ {
            tmp = int(test)
        }
        // Required by the compiler
        fmt.Print(tmp)
        end := time.Now()
        fmt.Print("Time elapsed: ", end.Sub(start))
    }
    

    Shows how inexpensive it is. Millions of conversions done in less than 3 msecs (my computer is a fairly powerful iMac but you get the point) which is probably mostly going into the iteration cycle rather than the cast.

    However, I would encourage you to use ints and play with your logic to ensure the values are correct (e.g. input validation which needs to be done for security reasons anyway).

    In C/C++ the type casting was automagic so you did not need to worry to cast between int and uint even though it was happening. In golang, you need to make it explicit but you are in the exact same situation but adding syntax problems.

    评论

报告相同问题?

悬赏问题

  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序