Is there a reason behind creating a Variable for the length of a String instead of using length() Java

java string variables string-length

86 просмотра

4 ответа

11 Репутация автора

I've been practicing Java on CodeBat. When I see other people solutions they create a variable for the length of a string. I was just wondering if there any advantages to creating the variable.

For example I'd write:

 for (int i = 1; i < str.length() - 1; i++) {
     if (str.charAt(i) == '*'  && str.charAt(i - 1) != str.charAt(i + 1)) {
         return false;

Others would write:

 int len = str.length();
 for (int i = 1; i < len - 1; i++) {
     if (str.charAt(i) == '*'  && str.charAt(i - 1) != str.charAt(i + 1)) {
         return false;
Автор: Milton Woody Jr. Источник Размещён: 22.08.2016 08:53

Ответы (4)

0 плюса

1 Репутация автора

Both approaches are appropriate, though the second would be preferable in cases where the length needs to be used again.

Автор: BKMaibach Размещён: 22.08.2016 08:56

3 плюса

5123 Репутация автора

There's absolutely no difference other than personal preferences:

  1. Strings are immutable in Java, so the length can never change.
  2. JIT compiler is smart enough to optimise length() call into a simple variable reading, so there will be no performance penalty.
Автор: Andrew Lygin Размещён: 22.08.2016 09:00

0 плюса

2303 Репутация автора

No there is not. The length of a java string is O(1) because java's string class stores the length as a field. So in the end it is nothing more than reading a variable. Thus, there will be no performance issue if you use .length()

The code for .length(), from JDK 1.6 is:

public int length() {
    return count;

Even if it is true that removing the call to the method may be seen as an optimisation, the JIT will probably do it dynamically anyway.

Perhaps in the solutions you have seen, people are writing code that way because they are use to coding in c.

Автор: LBes Размещён: 22.08.2016 09:00

0 плюса

199 Репутация автора

Your answer depends on how many times you might call the String.length() function & for readability purposes. If you are planning on using the value only once, there should be no need to create a variable to store the value. Otherwise if you will need to use the value more than once, it is more efficient to have a local variable instead of calling String.length() every time.

Ultimately, this goes back to personal preference more than anything else.

Автор: Abdulgood89 Размещён: 22.08.2016 09:03
Вопросы из категории :