true While和For(;;)哪个性能好?

有人愿意用While(true)因为他更清晰的看出来这里是个无限循环 。有人愿意用For(;;) , 因为有些IDE对于While(true)会给出警告 。至于你 , 爱用啥用啥!

true While和For(;;)哪个性能好?

文章插图
while(true)和for(;;)都是做无限循环的代码 , 他俩有啥区别呢?
我承认这个问题有点无聊 , 并且工作中也不会有人刻意的去考虑他们之间的性能差异 , 也不太会有人在做这个选择之间纠结 。
但是 , 最近竟然有很多面试官开始问这个问题 , 所以 , 那就索性理性分析一波 。
准备2段代码:
public class HollisTest {public static void mAIn(String[] args) {for(;;){System.out.println("this is hollis testing....");}}} 【true While和For(;;)哪个性能好?】public class HollisTest {public static void main(String[] args) {while (true){System.out.println("this is hollis testing....");}}}关于这个问题 , 网上有很多讨论 , 说那么多没用 , 直接反编译 , 看看字节码有啥区别就行了 。
分别将他们编译成class文件:
JAVAc HollisTest.java然后再通过javap对class文件进行反编译 , 然后我们就会发现 , 两个文件内容 , 一模一样!!!
Classfile /Users/hollis/workspace/chaojue/HLab/src/main/java/HollisTest.classLast modified 2023-6-18; size 463 bytesMD5 checksum 38eddb7d25748625d7c9aa377b6f66d3Compiled from "HollisTest.java"public class HollisTestminor version: 0major version: 52flags: ACC_PUBLIC, ACC_SUPERConstant pool:#1 = Methodref#6.#16// java/lang/Object."<init>":()V#2 = Fieldref#17.#18// java/lang/System.out:Ljava/io/PrintStream;#3 = String#19// this is hollis testing....#4 = Methodref#20.#21// java/io/PrintStream.println:(Ljava/lang/String;)V#5 = Class#22// HollisTest#6 = Class#23// java/lang/Object#7 = Utf8<init>#8 = Utf8()V#9 = Utf8Code#10 = Utf8LineNumberTable#11 = Utf8main#12 = Utf8([Ljava/lang/String;)V#13 = Utf8StackMapTable#14 = Utf8SourceFile#15 = Utf8HollisTest.java#16 = NameAndType#7:#8// "<init>":()V#17 = Class#24// java/lang/System#18 = NameAndType#25:#26// out:Ljava/io/PrintStream;#19 = Utf8this is hollis testing....#20 = Class#27// java/io/PrintStream#21 = NameAndType#28:#29// println:(Ljava/lang/String;)V#22 = Utf8HollisTest#23 = Utf8java/lang/Object#24 = Utf8java/lang/System#25 = Utf8out#26 = Utf8Ljava/io/PrintStream;#27 = Utf8java/io/PrintStream#28 = Utf8println#29 = Utf8(Ljava/lang/String;)V{public HollisTest();descriptor: ()Vflags: ACC_PUBLICCode:stack=1, locals=1, args_size=10: aload_01: invokespecial #1// Method java/lang/Object."<init>":()V4: returnLineNumberTable:line 1: 0public static void main(java.lang.String[]);descriptor: ([Ljava/lang/String;)Vflags: ACC_PUBLIC, ACC_STATICCode:stack=2, locals=1, args_size=10: getstatic#2// Field java/lang/System.out:Ljava/io/PrintStream;3: ldc#3// String this is hollis testing....5: invokevirtual #4// Method java/io/PrintStream.println:(Ljava/lang/String;)V8: goto0LineNumberTable:line 5: 0StackMapTable: number_of_entries = 1frame_type = 0 /* same */}SourceFile: "HollisTest.java"可以看到 , 两个用法 , 其实都是通过goto来干的 , 所以 , 这两者其实是没啥区别的 。用哪个都行
有人愿意用while(true)因为他更清晰的看出来这里是个无限循环 。有人愿意用for(;;) , 因为有些IDE对于while(true)会给出警告 。至于你 , 爱用啥用啥!




    推荐阅读