Should I check if an object exists in the collection before deleting it?

Say I have an object someObjectand NSMutableArray *someArray. I am not sure what someObjectis in the array, but if so, I want to delete it. There are two options:

Case 1:

if([someArray indexOfObject:someObject] != NSNotFound)
   [someArray removeObject:someObject];

Case 2:

[someArray removeObject:someObject];

In case 2, if the object does not exist in the array, nothing happens. My question is that case 2 is more efficient, since in case 1 I will need to search for the array and see if it exists, and if so, I delete it, but I assume that removeObject:it is looking for the array again?

+3
source share
4 answers

but I guess removeObject: is looking again for an array for this object?

, , . , . * :

indexOfObject: , removeObjectAtIndex:. [...] anObject, ( ).

, , removeObjectAtIndex: , .


* , ( O (log (N)), O (N)), NSArray . >

+6

, , . - , , ,

NSUInteger tempIndex = [someArray indexOfObject:someObject];
if (tempIndex != NSNotFound)
   [someArray removeObjectAtIndex:tempIndex]
else
   //in case it wasn't found...
+5

NSMutableArray ( ) "", , . indexOfObject, removeObject, , removeObject .

+2

case 2 removeObject,

indexOfObject: , removeObjectAtIndex:. , isEqual:. aObject, ( ).

so basically the two code examples are identical, except that the array can again perform another check after yours because it doesn’t know that you checked it, so this is just an extra processor time spent. But to be honest, I wouldn’t think too much about such examples now, but I’m just developing your application, and when it comes to optimizing, look at what takes up all the processor time and sets up such cases when they start to really take your time the processor.

0
source

All Articles