`
clark1231
  • 浏览: 248134 次
  • 性别: Icon_minigender_1
  • 来自: 苏州
社区版块
存档分类
最新评论

count vs length vs size

    博客分类:
  • ruby
阅读更多

 

In Ruby, #length and #size are synonyms and both do the same thing: they tell you how many elements are in an array or hash. Technically #length is the method and #size is an alias to it.

In ActiveRecord, there are several ways to find out how many records are in an association, and there are some subtle differences in how they work.

  • post.comments.count - Determine the number of elements with an SQL COUNT query. You can also specify conditions to count only a subset of the associated elements (e.g.:conditions => {:author_name => "josh"}). If you set up a counter cache on the association, #count will return that cached value instead of executing a new query.
  • post.comments.length - This always loads the contents of the association into memory, then returns the number of elements loaded. Note that this won't force an update if the association had been previously loaded and then new comments were created through another way (e.g.Comment.create(...)instead ofpost.comments.create(...)).
  • post.comments.size - This works as a combination of the two previous options. If the collection has already been loaded, it will return its length just like calling #length. If it hasn't been loaded yet, it's like calling #count.
a = { "a" => "Hello", "b" => "World" }
a.count  # 2
a.size   # 2
a.length # 2

a = [ 10, 20 ]
a.count  # 2
a.size   # 2
a.length # 2

For arrays and hashessizeis an alias forlength. They are synonyms and do exactly the same thing.

countis more versatile - it can take an element or predicate and count only those items that match.

> [1,2,3].count{|x| x > 2 }
=> 1

In the case where youdon'tprovide a parameter to count it has basically the same effect as calling length. There can be a performance difference though.

We can see from thesource code for Arraythat they do almost exactly the same thing. Here is the C code for the implementation ofarray.length:

static VALUE
rb_ary_length(VALUE ary)
{
  long len = RARRAY_LEN(ary);
  return LONG2NUM(len);
}

And here is the relevant part from the implementation ofarray.count:

static VALUE
rb_ary_count(int argc, VALUE *argv, VALUE ary)
{
  long n = 0;

  if (argc == 0) {
    VALUE *p, *pend;

    if (!rb_block_given_p())
      return LONG2NUM(RARRAY_LEN(ary));

    // etc..
  }
}

The code forarray.countdoes a few extra checks but in the end calls the exact same code:LONG2NUM(RARRAY_LEN(ary)).

Hashes (source code) on the other hand don't seem to implement their own optimized version ofcountso the implementation fromEnumerable(source code) is used, which iterates over all the elements and counts them one-by-one.

In general I'd advise usinglength(or its aliassize) rather thancountif you want to know how many elements there are altogether.


分享到:
评论

相关推荐

    《数据结构》算法实现及解析_高一凡(配合严蔚敏的数据结构)\严蔚敏数据结构习题集答案

    Status DeleteK(SqList &a,int ... if(va.length+1>va.listsize) return ERROR; va.length++; for(i=va.length-1;va.elem[i]>x&&i>=0;i--) va.elem[i+1]=va.elem[i]; va.elem[i+1]=x; return OK; }//Insert_SqList

    数据结构习题集答案

    if(va.length+1>va.listsize) return ERROR; va.length++; for(i=va.length-1;va.elem[i]>x&&i>=0;i--) va.elem[i+1]=va.elem[i]; va.elem[i+1]=x; return OK; }//Insert_SqList 2.12 int ListComp(SqList A...

    java五子棋源码

    java编的五子棋 import java.util.*; import java.io.*; import java.awt.*;... if(x+displace_x>=0 && x+displace_x<length && y+displace_y>=0 && y+displace_y<length && grid[x+displace_x][y+...

    CC1101芯片433M无线传输芯片STM32单片机设计驱动源码.zip

    unsigned char Spi_Read_Packet(unsigned char *Rx_buffer,unsigned char length); void Spi_Write_Packet(unsigned char *Tx_buffer,unsigned char size) ; void Spi_Write_Burst(unsigned char addr,unsigned char...

    动态Bitset源代码

    Bitset(const std::string & str, size_t _Pos, size_t _Count); public: size_t size()const; //返回设置为1的位数 size_t count() const; bool subscript(size_t _Pos) const; bool get(size_t pos) const; ...

    md5算法的c++实现

    void update(const unsigned char *buf, size_type length); void update(const char *buf, size_type length); MD5& finalize(); std::string hexdigest() const; friend std::ostream& operator(std::ostream...

    北大青鸟第二单元项目

    String countSql = "select count(*) from userinfo where 1=1"+conditionSql; pager.setTotalCount(getUserCount(countSql)); return list; } //查询条数 public int getUserCount(String sql){ int ...

    GifDecoder

    * @return iteration count if one was specified, else 1. */ public int getLoopCount() { return loopCount; } /** * Creates new frame image from current data (and previous * frames as specified ...

    用C#实现生成PDF文档(附源码)

    strPDFMessage="trailer << /Size "+ (xRefs.Count+1)+" /Root 6 0 R >> "; ConvertToByteAndAddtoStream(strPDFMessage); strPDFMessage="startxref " + streamStart+" %%EOF "; ConvertToByteAndAddtoStream...

    c# http post get

    requestHeaders.Add("Content-Length", postStream.Length.ToString()); requestHeaders.Add("Content-Type", "application/x-www-form-urlencoded"); requestHeaders.Add("Connection", "close"); ...

    MvcItem项目

    for (int i = 0; i < files.Count;... size = Math.Round(fb.ContentLength/1024.0)+"KB"; if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } fb.SaveAs(path + fileName); }

    jphp-torrent-ext:适用于jphp的JBit Torrent API

    $ i < count> length ); $ i ++) $ size += $ file -> length [ $ i ]; echo "-> Torrent info : \n" ; echo " -> CreatedBy : " . $ file -> createdBy . "\n" ; echo " -> CreationDate : " . $ file -> ...

    日历联动 java脚本

    selCity.length=count; } function Province_onchange() { FillCitys(g_selCity,g_selProvince.value); } function InitCitySelect(selProvince,selCity) { //alert("begin"); g_selProvince=selProvince...

    《深入学习c++string》2.1版

    1.5.6 string与count、count_if 15 1.6 string与wstring 15 1.6.1 简介 15 1.6.2 wstring实例 15 1.6.3 wstring与控制台 16 1.6.4 string与wstring的相互转换 17 1.7 string与C++流 22 1.7.1 C++流简介 22 1.7.2 ...

    计算机二级python常考题库.zip

    size() C. count() D. length() 下列关于Python变量的说法中,正确的是( ) A. 变量名必须以数字开头 B. 变量名区分大小写 C. 变量名可以使用Python关键字 D. 变量赋值后,其值不可改变 在Python中,以下哪个...

    用户名密码查询findpass

    DWORD Count; DWORD Unk04; DWORD Unk08; } PROCESS_INFO_HEADER, *PPROCESS_INFO_HEADER; typedef struct _PROCESS_INFO { DWORD LoadAddress; DWORD Size; DWORD Unk08; DWORD Enumerator; ...

    xml解析实例

    PIXELTYPEENUM_TYPECOUNT = 12 //"类型的数目" */ int pixelType; DPoint2 origin; DPoint2 finestResolution; IPoint2 finestSize;//最高level的栅格大小 IPoint2 blockSize; double lzts; int shareEdge...

    c/c++函数库说明(api)html版

    length (cppstring) #line (preproc) localtime (stddate) log (stdmath) log10 (stdmath) longjmp (stdother) lower_bound (cppmap) lower_bound (cppmultimap) lower_bound (cppmultiset) lower_bound ...

    php的敏感词的过滤类.zip

     }主要使用了 int substr_count ( string haystack, string needle [, int offset [, int length]] ) 这个方法,这个方法遍历待测的字符串$str中有没有$allergicWord数组中所包含的敏感词: 

    C#Windows视屏播放器

    float MyFileSize = (float)MyFileInfo.Length / (1024 * 1024); this.labeMp3Size.Text = MyFileSize.ToString().Substring(0, 6) + "M"; } catch { this.labeMp3Size.Text = ""; } } //保存播放列表 ...

Global site tag (gtag.js) - Google Analytics