Clear Optimisations

Life without a JITter is almost impossible. A lot of people tend to think that compiler optimisations are a myths and you shouldn’t really bother if the language you using is compiled or fully interpreted. Just have a look at this example to make sure that optimisations are real.

int even = 0;
int odd = 0;
long before;
long after;
before  = System.currentTimeMillis();

for (int i = 0; i < 10_000_000_00; i++) {
    if ((i & 0x1) != 0)
        even++;
     else
        odd++;
}
after = System.currentTimeMillis();
long t1 = (after-before);
System.out.println("t1="+t1); // ~10 ms on my machine

The reason why this ran super fast is because the compiler noticed that the computation within the loop is not needed in the program and hence it decided to skip the loop. Just prove it, use the computation and see the difference.

int even = 0;
int odd = 0;
long before;
long after;
before  = System.currentTimeMillis();

for (int i = 0; i < 10_000_000_00; i++) {
    if ((i & 0x1) != 0)
        even++;
     else
        odd++;
}
after = System.currentTimeMillis();
long t1 = (after-before);
System.out.println("t1="+t1); // ~1023 ms on my machine
System.out.println(even);
System.out.println(odd);

As you can see, it takes much more to execute (10x order of magnitude) simply because it is actually doing the computation.

Advertisements

Leave a Reply

Name and email address are required. Your email address will not be published.

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

You may use these HTML tags and attributes:

<a href="" title="" rel=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <pre> <q cite=""> <s> <strike> <strong> 

%d bloggers like this: