Есть что-то хитрое, что я не ловлю? Там, вероятно, есть ... ( edit: Да, есть!)
class AllInts {
public static void main(String[] args) {
// wrong -- i <= Integer.MAX_VALUE will never be false, since
// incrementing Integer.MAX_VALUE overflows to Integer.MIN_VALUE.
for (int i = Integer.MIN_VALUE; i <= Integer.MAX_VALUE; i++) {
System.out.println(i);
}
}
}
Поскольку печать является узким местом, буфер значительно улучшит скорость (я знаю, потому что я только что попробовал):
class AllInts {
public static void main(String[] args) {
// a rather large cache; I did no calculations to optimize the cache
// size, but adding the first group of numbers will make the buffer
// as large as it will ever need to be.
StringBuilder buffer = new StringBuilder(10000000);
int counter = 0;
// note that termination check is now <
// this means Integer.MAX_VALUE won't be printed in the loop
for (int i = Integer.MIN_VALUE; i < Integer.MAX_VALUE; i++) {
buffer.append(i).append('\n');
if (++counter > 5000000) {
System.out.print(buffer);
buffer.delete(0, buffer.length()-1);
counter = 0;
}
}
// take care of the last value (also means we don't have to check
// if the buffer is empty before printing it)
buffer.append(Integer.MAX_VALUE);
System.out.println(buffer);
}
}
Кроме того, эта версия фактически прекратит работу (спасибо Даниэлю Лью за то, что он указал, что на самом деле было что-то хитрое, что я не уловил).
Общее время выполнения для этой версии (с параметром -Xmx512m) составило 1:53. Это более 600000 номеров в секунду; совсем неплохо! Но я подозреваю, что это было бы медленнее, если бы я не запускал его свернутым.