0

I want to know if the length field of the array is kept internally as a value, or if it is calculated when called. Some sample code:

/* Makes several calls to string.length() in the body of the method */
String fooMyDataONE(String string, int queryLength) {
   if(string.length() == queryLength) {
      return workJobEquals(string);
   }
   else if(string.length() > queryLength) {
      return workJobGreaterThan(string);
   }
   // else string.length < queryLength
   return workJobLessThan(string);
}
/* Makes a single call to string.length() and stores it in a local variable */
String fooMyDataTWO(String string, int queryLength) {
   int actualLength = string.length();
   if(actualLength == queryLength) {
      return workJobEquals(string);
   }
   else if(actualLength > queryLength) {
      return workJobGreaterThan(string);
   }
   // else actualLength < queryLength
   return workJobLessThan(string);
}

So what would be the pros/cons between the two methods? As a side thought I would also like to know how a compiler might treat the two methods in a Java class. I really just want to understand how it is implemented, I can not find those details in the javadoc.

edit: The other thread would answer my question if my question was aimed at the Java level. My question is aimed at the implementation, more at the byte code / machine code level. I have read several similar questions with the same information, and none of them give any implementation details, which is my question.

GrannyF
  • 1
  • 2
  • Thanks on the field. Can you provide any details on exactly how this field is stored/accessed in the implementation? or any specifics about how a compiler may optimize the methods as shown in the post? – GrannyF Feb 27 '15 at 17:27
  • Implementation of what? It's a field like any other. See [this](http://stackoverflow.com/questions/12082196/string-length-vs-array-length) as well. – Sotirios Delimanolis Feb 27 '15 at 17:30
  • "Why is String.length() a method?" --- followed by --- "It's not a final public property because differing implementations exist" --- and further down the page ---- "the designers wanted to keep length as a property rather than a pseudo-method. (In part this may have made it easier for early Java implementations." --This never gives any of the internal details. Hmm, I apologize I do not know how to better word my question – GrannyF Feb 27 '15 at 17:45

0 Answers0