Check for array not empty: any?

后端 未结 6 1685
一整个雨季
一整个雨季 2020-12-12 11:32

Is it bad to check if an array is not empty by using any? method?

a = [1,2,3]

a.any?
=> true

a.clear

a.any?
=> false
<         


        
6条回答
  •  孤城傲影
    2020-12-12 12:15

    Avoid any? for large arrays.

    • any? is O(n)
    • empty? is O(1)

    any? does not check the length but actually scans the whole array for truthy elements.

    static VALUE
    rb_ary_any_p(VALUE ary)
    {
      long i, len = RARRAY_LEN(ary);
      const VALUE *ptr = RARRAY_CONST_PTR(ary);
    
      if (!len) return Qfalse;
      if (!rb_block_given_p()) {
        for (i = 0; i < len; ++i) if (RTEST(ptr[i])) return Qtrue;
      }
      else {
        for (i = 0; i < RARRAY_LEN(ary); ++i) {
            if (RTEST(rb_yield(RARRAY_AREF(ary, i)))) return Qtrue;
        }
      }
      return Qfalse;
    }
    

    empty? on the other hand checks the length of the array only.

    static VALUE
    rb_ary_empty_p(VALUE ary)
    {
      if (RARRAY_LEN(ary) == 0)
        return Qtrue;
      return Qfalse;
    }
    

    The difference is relevant if you have "sparse" arrays that start with lots of nil values, like for example an array that was just created.

提交回复
热议问题