简体   繁体   中英

Using includes() method when having only one element in an array is it efficient?

Does the below code blocks vary in performance especially when the array has only one element?

myArray.includes(anElement);

and

myArray.length === 1 && myArray[0] === anElement

Please tell which is a good coding practice and also tell about any performance issues in the above two scenarios.

When the array has only one element - the only difference is the length check. So if you are running this in a loop for a long time - probably you will see a difference because of that.

But the problem here is that you should not assume that the array has only one element unless you checked it previously, then it's the same.

If the array may contain more than one element, then the logic between these two is different and the comparison doesn't make sense.

Bottom line - to have them with the same logic you will do the same work. So just make it readable as @Xion 14 suggested.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM