在Golang中,uint16和int相比,哪个更节省成本?

huangapple go评论79阅读模式
英文:

In Golang, uint16 VS int, which is less cost?

问题

我正在使用一个64位服务器。我的golang程序需要整数类型。

所以,如果我在源代码中使用uint16和uint32类型,与使用最常见的int类型相比,是否会增加成本?

我正在考虑计算成本和开发成本。

英文:

I am using a 64Bit server. My golang program needs integer type.

SO, If I use uint16 and uint32 type in source code, does it cost more than use most regular int type?

I am considering both computing cost and developing cost.

答案1

得分: 14

对于绝大多数情况,使用int更合理。以下是一些原因:

  1. Go语言不会在数值类型之间进行隐式转换,即使你认为应该进行转换。如果你开始使用某个无符号类型而不是int,你应该预期在代码中频繁进行类型转换,因为其他库或API可能不支持无符号类型,因为无类型常量数值表达式返回的是int值,等等。
  2. 无符号类型比有符号类型更容易发生下溢,因为0(无符号类型的边界值)在计算机程序中更常见,例如-9223372036854775808。
  3. 如果你想使用无符号类型是因为它限制了可以放入其中的值,要记住当你结合了静默下溢和仅在编译时传播的常量时,你可能得不到你期望的效果。例如,虽然你不能将常量math.MinInt64转换为uint,但你可以轻松地将值为math.MinInt64int变量转换为uint。而且,对于你的程序来说,检查你尝试赋值的值是否有效可能并不是一个坏的Go风格。

除非你遇到了显著的内存压力,并且你的值空间略微超过较小有符号类型所提供的空间,否则我认为即使只考虑开发成本,使用int也会更高效。即使在这种情况下,很可能你的程序在内存占用方面存在其他问题,或者像Go这样的托管语言并不适合你的需求。

英文:

For the vast majority of cases using int makes more sense.
Here are some reasons:

  1. Go doesn't implicitly convert between the numeric types, even when you think it should. If you start using some unsigned type instead of int, you should expect to pepper your code with multiple type conversions, because of other libraries or APIs preferring not to bother with unsigned types, because of untyped constant numerical expressions returning int values, etc.
  2. Unsigned types are more prone to underflowing than signed types, because 0 (an unsigned type's boundary value) is much more of a naturally occurring value in computer programs than, for example, -9223372036854775808.
  3. If you want to use an unsigned type because it restricts the values that you can put in it, keep in mind that when you combine silent underflow and compile time-only constant propagation, you probably aren't getting the bargain you were looking for. For example, while you cannot convert the constant math.MinInt64 to a uint, you can easily convert an int variable with value math.MinInt64 to a uint. And arguably it's not a bad Go style to have an if check whether the value you're trying to assign is valid for your program.

Unless you are experiencing significant memory pressure and your value space is somewhere slightly over what a smaller signed type would offer you, I'd think that using int will be much more efficient even if only because of development cost.
And even then, chances are that either there's a problem somewhere else in your program's memory footprint, or a managed language like Go is not the best fit for your needs.

huangapple
  • 本文由 发表于 2016年3月22日 09:23:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/36144644.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定