This question prowadzić mnie, aby zrobić kilka badań:Null/Przedmiot i Null/Null sprawność porównanie
public class Stack
{
public static void main(String[] args)
{
Object obj0 = null;
Object obj1 = new Object();
long start;
long end;
double difference;
double differenceAvg = 0;
for (int j = 0; j < 100; j++)
{
start = System.nanoTime();
for (int i = 0; i < 1000000000; i++)
if (obj0 == null);
end = System.nanoTime();
difference = end - start;
differenceAvg +=difference;
}
System.out.println(differenceAvg/100);
differenceAvg = 0;
for (int j = 0; j < 100; j++)
{
start = System.nanoTime();
for (int i = 0; i < 1000000000; i++)
if (null == obj0);
end = System.nanoTime();
difference = end - start;
differenceAvg +=difference;
}
System.out.println(differenceAvg/100);
differenceAvg = 0;
for (int j = 0; j < 100; j++)
{
start = System.nanoTime();
for (int i = 0; i < 1000000000; i++)
if (obj1 == null);
end = System.nanoTime();
difference = end - start;
differenceAvg +=difference;
}
System.out.println(differenceAvg/100);
differenceAvg = 0;
for (int j = 0; j < 100; j++)
{
start = System.nanoTime();
for (int i = 0; i < 1000000000; i++)
if (null == obj1);
end = System.nanoTime();
difference = end - start;
differenceAvg +=difference;
}
System.out.println(differenceAvg/100);
}
}
styczna do other post, to warto zauważyć, jak wiele szybciej porównanie jest gdy Object
że porównujemy jest zainicjowany. Pierwsze dwie liczby w każdym wyjściu to: Object
, null
, a ostatnie dwie cyfry są po zainicjowaniu Object
. Wykonałem 21 dodatkowych wykonań programu, we wszystkich 30 wykonaniach, porównanie było znacznie szybsze po zainicjowaniu Object
. Co tu się dzieje?
Co to jest JVM? – fge
Ciekawe, można oczekiwać, że będzie działać odwrotnie. –
Używam Java 7.11. Pomyślałem, że to też będzie na odwrót. –