Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: does short take really 2 bytes?

Tags:

android

short

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];
like image 379
Dmitry Frank Avatar asked Jan 13 '12 19:01

Dmitry Frank


People also ask

Which is smaller byte or short?

short datatype is the variable range is more than byte but less than int and it also requires more memory than byte but less memory in comparison to int. The compiler automatically promotes the short variables to type int, if they are used in an expression and the value exceeds their range.

What is the point of short Java?

short: The short data type is a 16-bit signed two's complement integer. It has a minimum value of -32,768 and a maximum value of 32,767 (inclusive). As with byte , the same guidelines apply: you can use a short to save memory in large arrays, in situations where the memory savings actually matters.

What is the difference between int and byte?

A byte is the format data is stored in memory in past. 8 bits. An int is a format likewise you get it as value from the accumulator.


1 Answers

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.

like image 71
Ernest Friedman-Hill Avatar answered Sep 27 '22 17:09

Ernest Friedman-Hill