[英]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.
所以就像@Xion 14 建议的那样让它可读。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.