Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does storing the str.length() value in a variable before using it in a for loop have any performance improvements in Java?

Tags:

java

jvm

In short, does the JVM internally optimize the following code

public void test(String str)
{
    int a = 0;

    for( int i = 0; i < 10; i++)
    {
        a = a + str.length();
    }
}

to behave as efficiently as the one below:

public void test(String str)
{
    int len = str.length();
    int a = 0;

    for( int i = 0; i < 10; i++)
    {
        a = a + len;
    }
}

If it does optimize, does it do so by caching the str.length() value internally?

like image 287
deepak Avatar asked Dec 16 '14 03:12

deepak


People also ask

Can we use string in for loop?

For-loops can also be used to process strings, especially in situations where you know you will visit every character. While loops are often used with strings when you are looking for a certain character or substring in a string and do not know how many times the loop needs to run.

How do you use array length in a for loop?

As already mentioned, you can iterate through an array using the length attribute. The loop for this will iterate through all the elements one by one till (length-1) the element is reached (since arrays start from 0). Using this loop you can search if a specific value is present in the array or not.

Which is faster for loop or for-each loop Java?

Foreach performance is approximately 6 times slower than FOR / FOREACH performance. The FOR loop without length caching works 3 times slower on lists, comparing to arrays. The FOR loop with length caching works 2 times slower on lists, comparing to arrays.


1 Answers

nice answer Elliot F.

I did a much simpler test and ran the two methods with a very large number of repetitions and timed each.

The first method (where the length is only calculated once) was consistently faster than the second method.

Here's the whole test class I created;

package _testing;

import java.util.Date;

public class Speed {

    long count = 5000000;
    public static void main(String[] args) {

        long start, finish; 
        Speed sp = new Speed(); 

        start = new Date().getTime();
        sp.test("test");
        finish = new Date().getTime();
        System.out.println("test 1:"+(finish - start));

        start = new Date().getTime();
        sp.test2("test");
        finish = new Date().getTime();
        System.out.println("test 2:"+(finish - start));

    }


    public void test(String str) {
        int len = str.length();
        int a = 0;
        for (int i = 0; i < count; i++) {
            a = a + len;
        }
    }

    public void test2(String str) {
        int a = 0;
        for (int i = 0; i < count; i++) {
            a = a + str.length();
        }
    }   
}

The output looks like this;

test 1:7
test 2:22
like image 123
gts101 Avatar answered Oct 12 '22 23:10

gts101