Android: does short take really 2 bytes?

江枫思渺然 提交于 2020-01-14 09:52:28

问题


I am trying to make decision how to design my app.

I have about 300 instances of class just like this:

public class ParamValue {

   protected String sValue = null;
   protected short  shValue = 0;
   protected short  mode = PARAM_VALUE_MODE_UNKNOWN;

   /*
    * ...
    */
}

I have an array of these instances. I can't find out does these shorts really take 2 bytes or they take anyway 4 bytes?

And i need to pass the list of these objects via AIDL as a List<Parcelable>. Parcel can't readShort() and writeShort(), it can only work with int. So, to use short here too i have to manually pack two my shorts into one int, parcel it, and then unpack back. Looks too obtrusive.

Could you please tell me how many bytes shorts take, and does it make sense to use short instead of int here?

UPDATE:

I updated my question for future readers.

So, I wrote a test app and I figured out that in my case there's absolutely no reason to use short, because it takes the same space as int. But if I define array of shorts like that:

 protected short[] myValues[2];

then it takes less space than array of ints:

 protected int[] myValues[2];

回答1:


Technically, in the Java language, a short is 2 bytes. Inside the JVM, though, short is a storage type, not a full-fledged primitive data type like int, float, or double. JVM registers always hold 4 bytes at a time; there are no half-word or byte registers. Whether the JVM ever actually stores a short in two bytes inside an object, or whether it is always stored as 4 bytes, is really up to the implementation.

This all holds for a "real" JVM. Does Dalvik do things differently? Dunno.




回答2:


According to the Java Virtual Machine Specification, Sec. 2.4.1, a short is always exactly two bytes.

The Java Native Interface allows direct access from native code to arrays of primitives stored in the VM. A similar thing can happen in Android's JNI. This pretty much guarantees that a Java short[] will be an array of 2-byte values in either a JVM-compliant environment or in a Dalvik virtual machine.



来源:https://stackoverflow.com/questions/8855754/android-does-short-take-really-2-bytes

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!