84
35

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[Swift] count == 0 より isEmpty を使うべき理由

Last updated at Posted at 2017-02-26

小粒ネタです。Collectionクラスが空かどうか判定する際、count == 0よりisEmptyプロパティを使ったほうがいいのはなぜか答えられますか?

これは可読性だけの問題ではありません。
isEmptyのドキュメントにはこう書いてあります。1

When you need to check whether your collection is empty, use the isEmpty property instead of checking that the count property is equal to zero. For collections that don't conform to RandomAccessCollection, accessing the count property iterates through the elements of the collection.

要は、処理速度の問題です。

CollectionがRandomAccessCollectionでない場合、たとえばBidirectionalCollectionなどはcountの値を返すために要素を全て走査しないといけないので、**O(N)のオーダーになります。しかし、isEmptyは空かどうかをチェックするだけなのでどのようなCollectionでも常にO(1)**のパフォーマンスが期待でき、高速です。

まあ考えてみればそりゃそうだという話ですが、こういう細かいところも意識して良いコードを書けるようにしていきたいですね。

  1. https://developer.apple.com/reference/swift/collection/1641200-isempty

84
35
4

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
84
35

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?