-3

From the Code for String class I can see that length() returns value.length (here).

Lets say I want to print the length of a string str length() number of times.

Q1) What would be the better way to do it from the following code snippets: (if you have a better method please suggest)

Code 1:

public static void main(String[] args) {        
        String str="Hello World";
        for(int i=0;i<str.length();++i){
            System.out.println(str.length());
        }        
}

Code 2 (I prefer this one cause of the readability it offers about the program...)

public static void main(String[] args) {        
        String str="Hello World";
        final int len=str.length();
        for(int i=0;i<len;++i){
            System.out.println(len);
        }        
    }

Code 3:

public static void main(String[] args) {        
        String str="Hello World";
        int len=str.length();
        for(int i=0;i<len;++i){
            System.out.println(len);
        }        
    }

Q2) Which is the most optimized way OR are they the same ?

Q3) Does the compiler inline the length in the bytecode generated for this program ?

Thanks!

boxed__l
  • 1,334
  • 1
  • 10
  • 24
  • 5
    For a small program like this, you could compile the program and look at the bytecode. Follow along with the wiki article for byte code instructions. The JVM is a different story. – Sotirios Delimanolis Sep 10 '13 at 19:20
  • I don't get what you're trying to do... why would you want to print out the length of `str` 11 times? – StormeHawke Sep 10 '13 at 19:21
  • 1
    The time it takes to call `length()` is negligible compared to the time it takes to print out the result. – Henry Keiter Sep 10 '13 at 19:22
  • Something tells me I am not good at asking questions :| – boxed__l Sep 10 '13 at 19:25
  • @boxed__l No, its just that this isn't a very good question itself. Using correct formatting and all that does not make a question good. (Plus, this question shows you did absolutely no research - you need to at least google it first.) – AJMansfield Sep 10 '13 at 19:27
  • @StormeHawke : The code was intended to replace any trivial task..Main focus on length() vs assigning length() to a variable (micro optimizations as Oscar Lopez pointed out) – boxed__l Sep 10 '13 at 19:28
  • 4
    Just follow these simple rules: The First Rule of Program Optimization: *Don't do it*. The Second Rule of Program Optimization (for experts only!): *Don't do it yet*. – Oleg Pyzhcov Sep 10 '13 at 19:29
  • @VeriTi Well, that depends on what you are optimizing on the program. You should be optimizing for readability and reusability, not for speed. – AJMansfield Sep 10 '13 at 19:30
  • Please check [this](http://stackoverflow.com/questions/18725428/going-back-to-the-first-index-after-reaching-the-last-one-in-an-array) and tell me whether the point made by luis.espional is correct...(in comments section) – boxed__l Sep 10 '13 at 19:31
  • @AJMansfield and this is called *refactoring*, and usually is opposite for optimization, isn't it? – Oleg Pyzhcov Sep 10 '13 at 19:32
  • 1
    @boxed__l The two are somewhat different, in that by factoring out the `length()` call, you are allowing the compiler to replace the modulus division with parallel indexes, which it will. Here, factoring out the `length()` call will only eliminate one subtraction operation, which is not even nearly as intensive as a division. (They really shouldn't be doing it either, without actual performance tests showing it's necessary.) – AJMansfield Sep 10 '13 at 19:41
  • @AJMansfield : What do you mean by `modulus division with parallel indexes` ? – boxed__l Sep 10 '13 at 19:45
  • What I mean, is that instead of the compiler putting a modulus division instruction there, it will convert the code into doing something like the accepted answer's first two snippets. – AJMansfield Sep 10 '13 at 19:47
  • @AJMansfield : I want to clarify that this question was directed towards that link(Framing of this question was totally wrong). I should have profiled it(as pointed by Oscar Lopez) first before asking here :P thanks! – boxed__l Sep 10 '13 at 19:56

2 Answers2

4

General rule of java: don't optimize before you have performance issues.

Especially in cases like this one. You can think about performance of network connection or database. These things can take few seconds.

Marcin Szymczak
  • 11,199
  • 5
  • 55
  • 63
1

All the suggested snippets are micro-optimizations, and won't yield a noticeable performance improvement. For what is worth, here's yet another option...

final String str = "Hello World";
for (int i = 0, n = str.length(); i < n; ++i) {
    System.out.println(n);
}

What are the differences? that n is defined on the scope of the block where it's used, that ++i might be faster (this is open to discussion, see this question) and that the String object, being final, might be optimized for faster access by the compiler (and I'm speculating) but that's all. None of the snippets will be considerable faster than the others once the JIT compiler kicks in, what really matters is which one is easier to read and understand.

Regarding the two other questions: the three options (four counting mine) are practically equivalent, because the JIT infrastructure will probably store the length in a register of its own for the duration of the iteration, given that it's not changing and it's being used in a loop, so there's no point in doing the compiler's work by hand. Optimize for readability, forget about early optimizations (which are the root of all evil) and in case of doubt, profile first and optimize later.

Community
  • 1
  • 1
Óscar López
  • 232,561
  • 37
  • 312
  • 386