`
clark1231
  • 浏览: 253496 次
  • 性别: 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.


分享到:
评论

相关推荐

    RLE.zip_run_run length c++_run length coding

    Run Length Encoding(RLE)是一种简单的无损数据压缩算法,常用于处理连续重复的数据,比如图像数据中的背景颜色。在图像处理中,如果一个颜色连续出现多次,通过记录该颜色出现的次数,而不是连续写入相同的像素值...

    RLE.zip_RLE_encoding_run length c++_run length code_run length e

    在众多的压缩算法中,Run Length Encoding(RLE)是一种简单且高效的无损压缩方法。本文将深入探讨RLE编码的概念、原理、C++实现以及其在实际应用中的价值。 **一、RLE编码概述** Run Length Encoding(RLE)是...

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

    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

    Java-用数组实现栈-队列-线性列表

    return count == arrayLength; } public int size() { return count; } } ``` 在上面的代码中,我们使用一个数组 `array` 来存储队列中的元素,并使用 `head` 变量来记录队列的头部元素的索引,使用 `trail` ...

    array size (数组大小测量)2.zip_数组大小测量

    例如,`array size (数组大小测量)2.vi`可能是VI中一个专门用于计算数组大小的节点或子VI,它接收一个数组作为输入,然后输出该数组的长度。 总之,测量和理解数组大小对于编程是基础且关键的,它不仅影响代码的...

    java代码-Length

    3. **集合长度**: 对于Java集合框架中的List、Set和Queue等接口,它们没有直接的`length`属性,但提供了`size()`方法来获取元素数量。例如,对于ArrayList: ```java ArrayList<String> list = new ArrayList(); ...

    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+...

    delphi读取文件流

    SourceStream.Read(Buffer[0], Length(Buffer), Count); DestStream.Write(Buffer[0], Count); Offset += Count; end; finally SourceStream.Free; DestStream.Free; end; end; ``` 在这个改进版本中,我们...

    C#_TCP发送消息和传输文件

    int readLength = Math.Min(_blockLength, (int)(count - index)); stream.Read(clientData, 0, readLength); fs.Write(clientData, 0, readLength); index += readLength; } fs.Close(); } return true; }...

    数据结构期末考试模拟题

    if (src.length - srcPos < length || dst.length - dstPos < length) { throw new StringIndexOutOfBoundsException(length); } for (int i = 0; i < length; i++) { dst[dstPos++] = src[srcPos++]; } } ...

    C++上机编程测试纸质资料参考

    - `size_type find(const char *str, size_type index, size_type length);`:查找指定长度的子串。 - `size_type find(char ch, size_type index);`:查找单个字符`ch`。注意,`index`应为`string::size_type`...

    dotnet C# 将 Byte 二进制数组使用不安全代码快速转换为 int 或结构体数组.rar

    = 0) throw new ArgumentException("Byte array length must be a multiple of the size of MyStruct"); int count = bytes.Length / Marshal.SizeOf(); MyStruct* structArray = stackalloc MyStruct[count]; ...

    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...

    mysql数据库故障排除方案.pdf

    length / ( 1024 * 1024 * 1024 ), 2), 'G') idx,CONCAT(ROUND(( data_length + index_length ) / ( 1024 * 1024 * 1024 ), 2),'G') total_size,ROUND(index_length / data_length, 2) idxfracFROM information_...

    动态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; ...

    ios-自定义键盘头部.zip

    .text, let length = text.count, length > currentLength { currentLength = length if currentLength > maxLength { // 阻止输入或删除最后一个字符 textInput?.text = String(text.prefix(maxLength)) ...

    MySQL8.0优化Hint-在SQL中修改会话变量.pdf

    * max_error_count * max_execution_time * max_heap_table_size * max_join_size * max_length_for_sort_data * max_points_in_geometry * max_seeks_for_key * max_sort_length * optimizer_prune_level * ...

    iOS开发:BASE64转换,内含:IOS自带DES加解密

    let cryptData = NSMutableData(length: Int(data.count + kCCBlockSizeDES))! var numBytesEncrypted :size_t = 0 let status = CCCrypt(CCOperation.kCCEncrypt, CCAlgorithm.des, CCOptions(kCCOptionPKCS...

    ARM处理器下C语言编程效率优化.pdf

    if (size <= Count) { Count -= size;}`来替代,后者没有除法操作,执行效率更高。 优化除法运算的一种常见方法是用乘法替换除法。在表达式`radius = circle_length / (2 * PI)`中,可以定义一个宏`#define PI_...

    Java认证考试基础知识辅导Java程序性能优化

    int size = vector.size(); for (int i = 0; i < size; i++) { // 这里执行循环体 } } ``` 这样可以避免每次循环都重新计算向量的大小,从而提高程序的运行效率。 #### 初始化大小设置 当创建集合类如`Vector...

Global site tag (gtag.js) - Google Analytics