Следующий код на моей машине (Core2Duo 1.83Ghz, L2 cache 2Mb, ram 2Gb) с ключами запуска "-ea -Xmx256m -Xss64m" выдает:
1.751140997 sec
0.216811633 sec
Рекурсия работает очень медленно. Что с ней не так?
public class DoYouWantToSeeSomeMagic {
static class List {
List next;
public List(List next) {
this.next = next;
}
}
private static List createListSlow(int n) {
if (n == 0) {
return new List(null);
} else {
return new List(createListSlow(n - 1));
}
}
private static List createListFast(int n) {
List[] list = new List[n + 1];
list[0] = new List(null);
for (int i = 1; i <= n; ++i) {
list[i] = new List(list[i - 1]);
}
return list[n];
}
public static void main(String[] args) {
final int N = 1 << 20;
{
long time = System.nanoTime();
createListSlow(N);
System.err.println((System.nanoTime() - time) / 1e9 + " sec");
}
{
long time = System.nanoTime();
createListFast(N);
System.err.println((System.nanoTime() - time) / 1e9 + " sec");
}
}
}
Если я изменяю N на (1 << 19) то результат:
0.129561439 sec
0.129751965 sec
Я всегда думал, что в стандартных библиотеках все хорошо протестировано и работает безупречно. Моему удивлению не было предела, когда я увидел какие результаты выдал следующий код.
java.awt.geom
Class Line2D
ptLineDist
public static double ptLineDist(double X1,
double Y1,
double X2,
double Y2,
double PX,
double PY)
Returns the distance from a point to a line. The distance measured is the distance between the specified point and the closest point on the infinitely-extended line defined by the specified coordinates. If the specified point intersects the line, this method returns 0.0.
System.out.println(Line2D.ptLineDist(0, 0, 1, 200, 1, 199));
System.out.println(Line2D.ptLineDist(0, 0, 1, 2000, 1, 1999));
System.out.println(Line2D.ptLineDist(0, 0, 1, 20000, 1, 19999));
System.out.println(Line2D.ptLineDist(0, 0, 1, 200000, 1, 199999));
System.out.println(Line2D.ptLineDist(0, 0, 1, 2000000, 1, 1999999));
System.out.println(Line2D.ptLineDist(0, 0, 1, 20000000, 1, 19999999));
0.004999937545118085
5.000601076713239E-4
0.0 --- расстояние от точки (1,19999) до прямой (0,0) (1, 20000) равно 0 !!!
0.0
0.0
0.25 --- откуда здесь 0.25 ???
Кто может обьяснить такие странные результаты?







