Java: Convención de Bucle infinito [cerrado]
¿Cuál es la convención para un bucle infinito en Java? Debo escribir while(true)
o for(;;)
? Yo personalmente usaría while(true)
porque uso bucles while con menos frecuencia.
5 answers
No hay diferencia en bytecode entre while(true)
y for(;;)
pero prefiero while(true)
ya que es menos confuso (especialmente para alguien nuevo en Java).
Puede comprobarlo con este ejemplo de código
void test1(){
for (;;){
System.out.println("hello");
}
}
void test2(){
while(true){
System.out.println("world");
}
}
Cuando utilice command javap -c ClassWithThoseMethods
obtendrá
void test1();
Code:
0: getstatic #15 // Field java/lang/System.out:Ljava/io/PrintStream;
3: ldc #21 // String hello
5: invokevirtual #23 // Method java/io/PrintStream.println:(Ljava/lang/String;)V
8: goto 0
void test2();
Code:
0: getstatic #15 // Field java/lang/System.out:Ljava/io/PrintStream;
3: ldc #31 // String world
5: invokevirtual #23 // Method java/io/PrintStream.println:(Ljava/lang/String;)V
8: goto 0
Que muestra la misma estructura (excepto las cadenas" hello "vs" world").
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-01-06 01:11:13
Prefiero while(true)
, porque uso bucles while con menos frecuencia que los bucles for. Los bucles For tienen mejores usos y while(true)
es mucho más limpio y fácil de leer que for(;;)
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-11-11 21:41:17
Depende de ti. No creo que haya una convención para tal cosa. Puedes usar while(true)
o for(;;)
Diría que encuentro más a menudo while(true)
en los códigos fuente. for(;;)
se usa con menos frecuencia y es más difícil de leer.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-04-13 15:53:05
En última instancia, es su elección. La siguiente referencia Java utiliza el formato for (;;)
: La Instrucción for.
Sin embargo, while(true)
se usa más a menudo en bucles infinitos en mi experiencia.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-04-02 19:02:35
for(;;)
apesta, es completamente poco intuitivo leer para los novatos. Por favor, utilice while(true)
en su lugar.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-04-22 07:58:44