Which is preferable and cheaper: comparing classes with an exception?

Which is cheaper and preferable: put1 or put2?

Map<String, Animal> map = new Map<String, Animal>();

void put1(){
 for (.....)
  if (Animal.class.isAssignableFrom(item[i].getClass())
   map.put(key[i], item[i]);

void put2(){
 for (.....)
  try{
   map.put(key[i], item[i]);}
  catch (...){}

Question Version : The question was not so clear. Let me review the question a little. I forgot the casting, so put2 depends on the failure of the exception exception exception. isAssignableFrom (), isInstanceOf () and instanceof are functionally similar and, therefore, bear the same costs, one of them is a method of including subclasses, and the second for exact type matching, and the third is the version of the operator. Both reflexive methods and exceptions are expensive operations.

My question for those who have done some benchmarking in this area is which is cheaper and preferable: instanceof / isassignablefrom vs cast exception?

void put1(){
 for (.....)
  if (Animal.class.isAssignableFrom(item[i].getClass())
   map.put(key[i], (Animal)item[i]);

void put2(){
 for (.....)
  try{
   map.put(key[i], (Animal)item[i]);}
  catch (...){}
+3
5

, :

if (item[i] instanceof Animal)
    map.put(key[i], (Animal) item[i]);

, isAssignableFrom.

# ( #):

var a = item[i] as Animal;
if (a != null)
    map[key[i]] = a;

EDIT. - : instanceof cast-and-catch. . , ; , . , . , .

, item[i] Animal, , . instanceof, , : " Animal, ".

+12

. item[i] Animal, map.put(key[i], item[i]) ?

, , , , instanceof .

+2

, , , ( ), VM , .

tr/catch , , . , - , , , , , , Animal [] - , . .

+1

- .

, , , .

[i] Animal / ? , ? .

- , , [i] - , . .

: ( ):

: (1)

if ( aNumber < 100 ) {   
 processNumber(aNumber); 
}

(2)

try {
    processNumber(aNumber); //Throws exception if aNumber >= 100
} catch () {
}

, . (1) < 100 . (2) , processNumber , 100.

, (2) aNumber > 100. (1) aNumber > 100 , "-" , aNumber < 100.

PS - , , , .

+1
source

Your two alternatives are not really equivalent. Which one to choose depends entirely on what your code should do:

  • If the element will always be a Animal, then you should use put2(which will throw, if that is not the case ...)
  • If an element may or may not be Animal, you should use put1(which checks the condition, not the error ...)

Never mind performance first if you are writing code!

0
source

Source: https://habr.com/ru/post/1723439/


All Articles