在 .NET 中使用十进制或十六进制
早上好,下午好,晚上好,
预警:我知道这听起来像是我试图进行过早的优化,但我向你保证我不是。也就是说,如果您愿意尽力回答这个问题,而不是向我指出有关“过早优化”的链接,请回答这个问题。
是否有可能注意到使用以十进制和十六进制编写的常量进行大量重复操作的性能差异?我看到人们写了
int b = a >> 0x1f;
很多文章,而不是
int b = a >> 31;
表明他们要么来自 C/C++ 背景,要么他们可能认为操作执行得更快(而且我不仅仅谈论按位操作)。 C# 编译器不是将所有常量转换为相同的基数吗?或者在编写代码时使用 16 进制比 10 进制有什么优势吗?
非常感谢,
Good morning, afternoon or night,
Forewarning: I know that this may sound like I am trying to do premature optimization, but I assure you I am not. That being, please answer this question if you would like to to the best of your ability without pointing me to links about "premature optimization".
Is it possible to notice any differences in the performance of massively repeated operations using constants written in base ten and in base sixteen? I see people writing
int b = a >> 0x1f;
a lot instead of
int b = a >> 31;
which suggests that either they come from a C/C++ background or that they may think operations perform faster (and I am not talking only about bitwise operations). Aren't all constants translated to the same base by the C# compiler? Or can there be any advantages in using base 16 over base 10 while writing code?
Thank you very much,
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
这没有什么区别,因为它们会被编译成相同的东西。
它确实使二进制运算的代码更具可读性,因为使用十六进制可以更轻松地读取这些位。从十进制转换 ->二进制在心理上更难实现。
0x1f 将是:
1 -> 0001
+
f-> 1111
= 00011111
It will make no difference as they will get compiled down to the same thing.
It does make the code more readable for binary operations as using hexadecimal makes it easier to read the bits. To convert from decimal -> binary is a lot harder to do mentally.
0x1f is going to be :
1 -> 0001
+
f -> 1111
= 00011111
这两个语句对于编译器来说是相同的。这只是用户偏好的问题。
Those two statements are identical to the compiler. It's just a matter of user preference.
唯一的优点是对于习惯使用十六进制工作的人来说更容易阅读。整数就是整数,无论是用十进制文字还是十六进制表示。
The only advantage is that it's more readable to someone who's used to working in hex. An integer is an integer, whether represented by a decimal literal, or a hex one.
我看到的唯一优点是按位运算通常在十六进制中更有意义。然而,转变操作却没有(在我看来)。
The only advantage I see is that bitwise operations typically make more sense in hex. The shift op, however, doesn't (in my opinion).
它们在 IL 中确实被解释为完全相同的东西,并且第一个对于大多数人来说更难阅读。所以hex方法没有太大优势。
They are indeed interpreted as the exact same thing in the IL, and the first is harder to read for most people. So there's not much advantage to the hex method.
数字就是数字,十进制或十六进制只是以人类可读的方式将数字写在屏幕上的表示形式。所以根本没有区别,在c/c++中也是如此。
A number is a number, decimal or hex is just a representation to write the number on the screen in a way human can read. So there is no difference at all, neither in c/c++.