英文:
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
更合理。以下是一些原因:
- Go语言不会在数值类型之间进行隐式转换,即使你认为应该进行转换。如果你开始使用某个无符号类型而不是
int
,你应该预期在代码中频繁进行类型转换,因为其他库或API可能不支持无符号类型,因为无类型常量数值表达式返回的是int
值,等等。 - 无符号类型比有符号类型更容易发生下溢,因为0(无符号类型的边界值)在计算机程序中更常见,例如-9223372036854775808。
- 如果你想使用无符号类型是因为它限制了可以放入其中的值,要记住当你结合了静默下溢和仅在编译时传播的常量时,你可能得不到你期望的效果。例如,虽然你不能将常量
math.MinInt64
转换为uint
,但你可以轻松地将值为math.MinInt64
的int
变量转换为uint
。而且,对于你的程序来说,检查你尝试赋值的值是否有效可能并不是一个坏的Go风格。
除非你遇到了显著的内存压力,并且你的值空间略微超过较小有符号类型所提供的空间,否则我认为即使只考虑开发成本,使用int
也会更高效。即使在这种情况下,很可能你的程序在内存占用方面存在其他问题,或者像Go这样的托管语言并不适合你的需求。
英文:
For the vast majority of cases using int
makes more sense.
Here are some reasons:
- 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 returningint
values, etc. - 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.
- 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 auint
, you can easily convert anint
variable with valuemath.MinInt64
to auint
. And arguably it's not a bad Go style to have anif
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论