Skip to content

JDK7: Strings in switch

December 29, 2012

If you read what Oracle wrote about using Strings in switch statements now, you’d see that they say that switch statements produce more efficient bytecode than the equivalent if-then-else statements. WARNING: This post compares things at the JVM bytecode, may not be tolerable for all readers.

Let’s compare the new approach of using JDK7 Strings inside of a switch statement, and using the well-known if-then-else approach we all know and use. Below is an example class with 2 methods illustrating each approach.

If you compile this Switch.java class and then decompile it:


javac Switch.java
javap -c Switch

You can see this output:

Let’s tally up the bytecodes for each approach:

switchTest method: 44 bytecodes

7 ldc, 5 goto, 5 astore_2, 4 istore, 4 invokevirtual, 4 aload_3, 3 ifeq, 1 tableswitch, 1 lookupswitch, 1 iload, 1 iconst_m1, 1 iconst_2, 1 iconst_1, 1 iconst_0, 1 astore_3, 1 areturn, 1 aload_2, 1 aload_1, 1 aconst_null

ifThenElseTest method: 27 bytecodes

7 ldc, 5 astore_2, 3 invokevirtual, 3 ifeq, 3 goto, 3 aload_1, 1 areturn, 1 aload_2, 1 aconst_null

So to me, switching on constant Strings does not look more efficient.

Advertisements

From → Java

Leave a Comment

Leave a Reply

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s

%d bloggers like this: