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?
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With