Variable storage compared to several different methods

What are the pros and cons of using this:

String a = new String(); switch (i) { case 1: a = "Cueck"; break; case 2: a = "Blub"; break; case 3: a = "Writing cases is BORING!"; break; } System.out.println(a); 

Versus:

 switch (i) { case 1: System.out.println("Cueck"); break; case 2: System.out.println("Blub"); break; case 3: System.out.println("Writing cases is BORING!"); break; } 

What generates the best bytecode? And what generates more bytecode?

+4
source share
3 answers

Using javap -c classname , you can check the bytecode yourself,

Here is option 1:

(Note: I had to initialize a = null , otherwise it will not compile)

  7: aconst_null 8: astore_2 9: iload_1 10: tableswitch{ //1 to 3 1: 36; 2: 42; 3: 48; default: 51 } 36: ldc #3; //String Cueck 38: astore_2 39: goto 51 42: ldc #4; //String Blub 44: astore_2 45: goto 51 48: ldc #5; //String Writing cases is BORING! 50: astore_2 51: getstatic #6; //Field java/lang/System.out:Ljava/io/PrintStream; 54: aload_2 55: invokevirtual #7; //Method java/io/PrintStream.println:(Ljava/lang/String;)V 58: return 

Here is option 2:

  7: iload_1 8: tableswitch{ //1 to 3 1: 36; 2: 47; 3: 58; default: 66 } 36: getstatic #3; //Field java/lang/System.out:Ljava/io/PrintStream; 39: ldc #4; //String Cueck 41: invokevirtual #5; //Method java/io/PrintStream.println:(Ljava/lang/String;)V 44: goto 66 47: getstatic #3; //Field java/lang/System.out:Ljava/io/PrintStream; 50: ldc #6; //String Blub 52: invokevirtual #5; //Method java/io/PrintStream.println:(Ljava/lang/String;)V 55: goto 66 58: getstatic #3; //Field java/lang/System.out:Ljava/io/PrintStream; 61: ldc #7; //String Writing cases is BORING! 63: invokevirtual #5; //Method java/io/PrintStream.println:(Ljava/lang/String;)V 66: return 

Personally, I do not think that the bytecode is better in this case, I consider option 1 to be more readable.

+4
source

Your first option is tidier and has less redundant code. One of the proposed changes:

 String a; switch (i) { case 1: a = "Cueck"; break; case 2: a = "Blub"; break; case 3: a = "Writing cases is BORING!"; break; default: throw new IllegalStateException("Unknown option!"); } System.out.println(a); 

Do not create String unnecessarily - a should be set as needed. The default case should either throw an exception or set a to the default value.

What generates the best bytecode? And what generates more bytecode?

I would not worry about that. This does not seem to me a likely bottleneck in any real application. In addition, you cannot be sure what the JVM will do to optimize the byte code after starting your application.

+5
source

I don’t think there will be a big difference in the size of the bytecode, but I propose the first approach. If in some future code changes you decided not to call System.out.println(a) , but logger.debug(a) , you will change this only to one place, and not to the whole case .

+4
source

All Articles