简体   繁体   English

在Java中使用常数1中的按位移位的优势

[英]Advantage of using bitwise shifting in constant 1 in java

in android source code, there is something like below. 在android源代码中,有类似下面的内容。 Is there any good reason to use bitwise shifting in this situation? 在这种情况下是否有充分的理由使用按位移位? Wouldn't be simpler just typing 1 ? 只需输入1会更简单吗?

public static final int POP_BACK_STACK_INCLUSIVE = 1<<0;

What is the disadvantage of using like below or advantage of above? 像下面这样使用或上面那样使用的缺点是什么?

public static final int POP_BACK_STACK_INCLUSIVE = 1;

This was done not for performance but for maintenance of the code. 这样做不是为了提高性能,而是为了维护代码。

Upon compilation compiler evaluates constant expressions, and this constant will be stored as 1 编译后,编译器将评估常量表达式,并且此常量将存储为1

But in future, when this constant should be changed via shifting, the maintainer will just change 0 to another number in the source code. 但是将来,当应通过移位更改此常数时,维护者将在源代码中仅将0更改为另一个数字。

Shift operator just shows to maintainer, that shift operation can be used for this constant in the future releases. Shift运算符只是向维护人员表明,在将来的版本中,该常数可以使用shift运算。

There is no performance advantage for either version. 两种版本都没有性能优势。 In the first case, the 1<<0 expression is evaluated at compile time, and the Java and Dalvik bytecodes will actually just use a constant 1 ... in both case. 在第一种情况下, 1<<0表达式在编译时求值,而Java和Dalvik字节码实际上将只使用常量1 ...。

The real reason is to document that this is a "bit flag" value. 真正的原因是要证明这是一个“位标志”值。 Writing the expression as 1<<0 is saying that the flag has bit zero set. 将表达式写为1<<0表示该标志已设置为零位。


Note that this does NOT give the developers the option of changing the shifting in some future version. 请注意,这不会为开发人员提供在将来的某些版本中更改班次的选项。 POP_BACK_STACK_INCLUSIVE is a public compile-time constant, so changing it could lead to binary compatibility problems. POP_BACK_STACK_INCLUSIVE是一个公共的编译时常量,因此更改它可能会导致二进制兼容性问题。 Specifically, code that is compiled against different versions of Android would have different values for the constant. 具体来说,针对不同版本的Android编译的代码的常量值将有所不同。 That could make apps non-portable across different Android releases; 这可能会使应用无法在不同的Android版本之间移植。 ie you would need different versions of apps for the different releases. 也就是说,对于不同的版本,您将需要不同版本的应用程序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM