Конструкция try/catch обходится дороже. Приведу тест замера времени для 1000000000 вызовов методов проверяющих аргумент на null
явно и в попытке и выведу результат замера в консоль:
public class Test {
public static void main(String[] args) {
long start, end;
start = System.currentTimeMillis();
for (int i = 0; i < 1000000000; i++)
method(null);
end = System.currentTimeMillis();
System.out.println("Check null: " + (end-start));
start = System.currentTimeMillis();
for (int i = 0; i < 1000000000; i++)
methodWithTry(null);
end = System.currentTimeMillis();
System.out.println("Try/catch: " + (end-start));
}
public static int method(String s) {
if (s != null) {
return s.length();
}
return 0;
}
public static int methodWithTry(String s) {
try {
return s.length();
} catch (NullPointerException e) {
return 0;
}
}
}
Результат:
Check null: 15
Try/catch: 1404
UPD:
Комментарий Artem Konovalov подтвердился. Судя по всему мой код был автоматически оптимизирован из-за того, что не был использован результат методов. Скорректированный код дает иные результаты:
public class Test {
public static void main(String[] args) {
int c = 0;
long start, end;
start = System.currentTimeMillis();
for (int i = 0; i < 1000000000; i++)
if (i%2==0) {
c += method(null);
} else {
c += method(i);
}
end = System.currentTimeMillis();
System.out.println("Check null: " + (end-start));
start = System.currentTimeMillis();
for (int i = 0; i < 1000000000; i++)
if (i%2==0) {
c += methodWithTry(null);
} else {
c += methodWithTry(i);
}
end = System.currentTimeMillis();
System.out.println("Try/catch: " + (end-start));
}
public static int method(Integer i) {
if (i != null) {
return i.intValue();
}
return 0;
}
public static int methodWithTry(Integer i) {
try {
return i.intValue();
} catch (NullPointerException e) {
return 0;
}
}
Результат:
Check null: 1702
Try/catch: 3654
if (a == null) throw new IllegalArgumentException("a == null");
if (b == null) throw new IllegalArgumentException("b == null");
И сразу видно с чем проблема. И даже более глубокий смысл появляется вместо абстрактного NPE. Неправильный аргумент, а что ты хотел? – Sergey 27 дек '16 в 8:10