Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is using hard-coded integer values in code a BAD practice from memory considerations

Tags:

java

jvm

Consider a simple following code in Java:

void func(String test)
{
    if(str.length() > 0)
    {
       //do something
    }
}

Does executing str.length() > 0 means that every time this function is called, 4 bytes of memory will be allocated to store 0 integer value ?

like image 629
sky Avatar asked Apr 16 '26 13:04

sky


1 Answers

The memory needed to run this function (including the 0) would be part of the compiled program (.class / .jar/.apk), and has nothing to do with how many times the function is run. Even if the function is inlined, only the code size grows based on how many different locations the function is called, and there is NO memory allocation in run time, while the code runs.

Meanwhile 2 comments

  • There are far bigger issues with hardcoding.
  • I doubt length > 0 counts as hardcoding in any but the strictest sense.
like image 90
Karthik T Avatar answered Apr 19 '26 02:04

Karthik T