2

Mostly, I use Int, Double and String, Char. Recently, I got interested in saving memory and I realized even small amount of bytes can be much larger and it affects the program and even the mobile speed and battery life.(Especially, data resources of its memory)

So, I am trying to use Byte, Short when the data doesn't need to store big numbers. For example, byte for -128 ~ 127, Short for -32,768 ~ 32,767.

Is it a good idea?

And My main question is I want to know the data type of const val in Kotlin since it automatically defines the datatype.

const val THIS_IS_STRING = "HelloWorld"
const val THIS_IS_CHAR = 'C'
const val NUMBER_1 = -124
const val NUMBER_2 = 31000
const val NUMBER_3 = 1000000
const val NUMBER_4 = 1232188777777344444
const val NUMBER_5 = 29128812312732881231273712
const val NUMBER_6 = 0.423
const val NUMBER_7 = 0.2121222222441
const val NUMBER_8 = 0.813881281237123991827312324
const val NUMBER_9 = 0.5123090982307037412398190092340239423094803820432423423209823092342342348209384023984023480923840923840009930923094029848901

What are the data types of them(The numbers)?

Or should I define like these for saving the resources? Or I don't need to?

const val MIN:Byte = -124
const val MID:Short = 31000
const val MAX:Int = 1000000
...
``
Anoop M Maddasseri
  • 10,213
  • 3
  • 52
  • 73
c-an
  • 3,543
  • 5
  • 35
  • 82
  • const val is a top-level `static` member (since static doesn't exist in Kotlin.) – Ashish Jun 29 '20 at 06:36
  • @Ashish does it mean they don't have any data types? When I use the constant numbers, it gives error when the types aren't matched each other. For instance, `setString(NUMBER_9)`. So, It may have something like data type. How does 'static' work? – c-an Jun 29 '20 at 06:39
  • it means you have to provide value before compiling. It's like static variable let me provide you example – Ashish Jun 29 '20 at 06:39
  • [At a glance, Val vs Const](https://stackoverflow.com/a/61836712/4694013) – Anoop M Maddasseri Jun 29 '20 at 06:53
  • What do you want to say? Those are not the answers for my question. I am talking about data types for memory. – c-an Jun 29 '20 at 06:57
  • 1
    @AnoopM his main question is do he need to set the resource type or it will automatically allocated by kotlin ? – Ashish Jun 29 '20 at 06:57
  • 1
    @c-an people got confused with your question. It's related to providing the resource type but mostly people read question and check code. So i read your concern and let me find the solution is it good or bad to provide resources – Ashish Jun 29 '20 at 06:58

5 Answers5

2

It is dependent on you whether you want to provide data type allocation to kotlin or self. If your saving the values by providing resource type. You can save data or you can depend on the kotlin.

But if your saving the data i will advice you to provide the data type :

Let's take this as an example for you :

fun main() {
    var b: Any = 124
    println(b)
    if(b is Float) {
        println("Float")
    }
    else if(b is Double) {
        println("Double")
    }else if(b is Byte){
        println("byte")
    }else if(b is Int){
        println("int")
    }else if(b is Short){
        println("short")
    }
}

It will provide the output as Int.

So i suggest provide data type.

Ashish
  • 6,791
  • 3
  • 26
  • 48
  • It is static so, I don't want to change. And it is not supposed to. I just want to know if I need to set like `const val MAX:Byte = 26` (specifying the data type) for using less memory resource. Or it is automatically set the data as small as it can store without breaking it. – c-an Jun 29 '20 at 06:51
  • Oh, So, I must write the data type at the end.. That's clear. Thanks. – c-an Jun 29 '20 at 07:33
1

Kotlin Type inference  -  In Kotlin most of the time, you won't need to specify the type of the objects you are working with, as long as the compiler can infer it.

So, we just need to write var or val depending on the type of variable we want to generate, and the type can normally be inferred. We can always specify a type explicitly as well. Say, for instance, you define val REQUEST_CODE = 100. Behind the scenes, REQUEST_CODE initializes with the Int datatype since the value of REQUEST_CODE is of type Int, the compiler infers that REQUEST_CODE is also a Int. Note that Kotlin is a statically-typed language. This means that the type is resolved at compile time and never changes.

Although Kotlin uses Type Inference ( automatically identify something ), which means we also have the option to specify the data type when we initialize the variable like below:

val REQUEST_CODE: Int = 100

Both act the same while converting it to byte code.

What the heck, How do Kotlin determine the data type of numbers if we use implicit declaration?

Good question, Kotlin provides a set of built-in types that represent numbers. For integer numbers, there are four types with different sizes and, hence, value ranges.

enter image description here

All variables initialized with integer values not exceeding the maximum value of Int have the inferred type Int. If the initial value exceeds this value, then the type is Long. To specify the Long value explicitly, append the suffix L to the value. So, whenever you strictly want to save memory it is advisable to use explicit type declaration for data types like Byte & Short as mentioned by Animesh in the accepted answer.

val one = 1 // Int
val threeBillion = 3000000000 // Long
val oneLong = 1L // Long
val oneByte: Byte = 1

Reference

Anoop M Maddasseri
  • 10,213
  • 3
  • 52
  • 73
  • Oh.. Thanks. So, even if I define it as Byte, all the numbers acts like Integer. That sounds weird... So, writing `:DATA_TYPE` is meaningless.. on the other way, it means Kotlin isn't a good language for managing the memory resource. – c-an Jun 29 '20 at 07:37
  • 1
    `So, even if I define it as Byte, all the numbers act like Integer` - I didn't mean that. I compared `const Val NUMBER_1: Int = -124` against `const Val NUMBER_1 = -124`. There was a Typo in the answer, corrected! Thanks. – Anoop M Maddasseri Jun 29 '20 at 07:55
  • What do you think about [this answer](https://stackoverflow.com/questions/62632430/what-is-the-type-of-const-val-num-1-of-kotlin-and-how-are-they-able-to-defi#answer-62638127)? – c-an Jul 01 '20 at 01:25
1

Type inference is described in https://kotlinlang.org/docs/reference/basic-types.html

Basically the default types when not specified for a number in range of -231 to 231-1 is Int and higher than that is Long. To specify the Long value explicitly, append the suffix L to the value. So, whenever you strictly want to save memory it is advisable to use explicit type declaration for Byte and Short.

val one = 1                    // inferred as Int
val threeBillion = 3000000000  // inferred as Long
val oneL = 1L                  // explicitly specify Long type by appending with L
val oneLong: Long = 1L         // explicitly specify Long by type
val oneByte: Byte = 1          // explicitly specify Byte for saving memory

For floating point numbers default type is Double, you can switch to float by either specifying type or appending f.

val pi = 3.14               // Double
val piFloat: Float = 3.14   // explicitly specify Float by type
val e = 2.7182818284        // Double
val eFloat = 2.7182818284f  // explicitly specify Float by appending with f

The characters and strings by nature having single data type so it is Char and String by default, and there is no need to change it explicitly.

It is generally Advisable to specify types to save memory because it is constant and will never change so conservation is a better choice, but it is all upto you.

Anoop M Maddasseri
  • 10,213
  • 3
  • 52
  • 73
Animesh Sahu
  • 7,445
  • 2
  • 21
  • 49
  • It is incorrect that a `Short` or `Byte` property saves memory compared to an `Int`. https://stackoverflow.com/a/1541484/506796 I don't think it matters with `const` either, since their usages are inlined. – Tenfour04 Jun 29 '20 at 13:08
  • @Tenfour04 I read in some other stackoverflow as well that it does not save memory but still [oracle docs](https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html#:~:text=It%20has%20a%20minimum%20value,the%20memory%20savings%20actually%20matters.&text=short%3A%20The%20short%20data%20type,bit%20signed%20two's%20complement%20integer.) state that it indeed saves memory, there's some controversy imo. – Animesh Sahu Jun 29 '20 at 13:18
  • It says they save memory *in arrays*. They are aligned by bytes in arrays. When they are in a bare variable, they are aligned by word size (every 4 or 8 bytes). There might be some special JVM out there for ultra low-end devices that doesn’t do that, but I think OP is talking about Android. – Tenfour04 Jun 29 '20 at 13:21
1

I’m surprised there are so many answers here ignoring this, but using Byte and Short for properties will not save you memory. The backing variables still take up 4 bytes of memory for each. They only save you memory when you use them in ByteArray and ShortArray. They also can cause a performance penalty for doing arithmetic with them instead of Int or Long, but that’s insignificant in most applications.

As other answers have mentioned Int is implicit unless the number is big enough to be a Long. And this is what you want because it is more performant and takes up the same amount of memory.

Tenfour04
  • 83,111
  • 11
  • 94
  • 154
  • what about Java? – c-an Jul 01 '20 at 01:18
  • 1
    @c-an Java has the same limitation. It has to do with the VM, not the language itself. Modern VM's like the one used by Android have no reason to make such a trivial optimization for a few variables. When a device has a GB of RAM, it is a waste of your time to worry about saving individual bytes. It could only possibly be useful when you have 10,000's of something, and then if it really matters, you can put the work in to optimize using ByteArrays and ShortArrays. This is not a common need. – Tenfour04 Jul 01 '20 at 01:31
  • 1
    Think about it this way. If you display an image on your screen, 480x480 pixels, it will use over 900,000 bytes of RAM. You would have to convert 230,000 of your Ints into Bytes to save as much as that. And modern phones do not struggle with some little image like that. That's much smaller than many of the images you see in popular apps. There is no motivation to do what you're describing. – Tenfour04 Jul 01 '20 at 01:34
  • Oh, I see. So, when I do program, speed is the priority than memory in code level. And for the images or other files, the matter is compression. – c-an Jul 01 '20 at 01:50
  • 1
    Yes, but the compression of images at run time is very low level. Android's view system would be handling that under the hood. For example, using heavier compression on a JPG has no impact on the memory it takes up when it's transferred to the GPU. – Tenfour04 Jul 01 '20 at 02:34
-1

Const is a compilation time constant. This means that a value must be allocated during the compilation time, unlike the value that can be performed at run-time, meaning that the const cannot be assigned to a function or class constructor and should only be allocated as character series or basic data type.

S T
  • 1,068
  • 2
  • 8
  • 16