26 Dec 2013

ObjectSpace in ruby contains many useful heap debugging utilities.

Since 1.9 ruby has included  objspace.so which
adds even more methods to the ObjectSpace module:

ObjectSpace.each_object{ |o| ... }
ObjectSpace.count_objects #=> {:TOTAL=>55298, :FREE=>10289, :T_OBJECT=>3371, ...}

require 'objspace'
ObjectSpace.memsize_of(o) #=> 0 /* additional bytes allocated by object */
ObjectSpace.count_tdata_objects #=> {Encoding=>100, Time=>87, RubyVM::Env=>17, ...}
ObjectSpace.count_nodes #=> {:NODE_SCOPE=>2, :NODE_BLOCK=>688, :NODE_IF=>9, ...}
ObjectSpace.reachable_objects_from(o) #=> [referenced, objects, ...]
ObjectSpace.reachable_objects_from_root #=> {"symbols"=>..., "global_tbl"=>...} /* in 2.1 */

In 2.1, we've added a two big new features: an allocation tracer and a heap dumper.

Allocation Tracing

Tracking down memory growth and object reference leaks is tricky when you don't know where the objects are coming from.

With 2.1, you can enable allocation tracing to collect metadata about every new object:

require 'objspace'
ObjectSpace.trace_object_allocations_start

class MyApp
  def perform
    "foobar"
  end
end

o = MyApp.new.perform
ObjectSpace.allocation_sourcefile(o) #=> "example.rb"
ObjectSpace.allocation_sourceline(o) #=> 6
ObjectSpace.allocation_generation(o) #=> 1
ObjectSpace.allocation_class_path(o) #=> "MyApp"
ObjectSpace.allocation_method_id(o)  #=> :perform

A block version of the tracer is  also available .

Under the hood, this feature is built on  NEWOBJ and  FREEOBJ tracepoints
included in 2.1. These events are only available from C, via rb_tracepoint_new() .

Heap Dumping

To further help debug object reference leaks, you can dump an object (or the entire heap) for offline analysis.

require 'objspace'

# enable tracing for file/line/generation data in dumps
ObjectSpace.trace_object_allocations_start

# dump single object as json string
ObjectSpace.dump("abc".freeze) #=> "{...}"

# dump out all live objects to a json file
GC.start
ObjectSpace.dump_all(output: File.open('heap.json','w'))

Objects are serialized as simple json, and include all relevant details about the object, its source (if allocating tracing was enabled), and outbound references:

{
 "address":"0x007fe9232d5488",
 "type":"STRING",
 "class":"0x007fe923029658",
 "frozen":true,
 "embedded":true,
 "fstring":true,
 "bytesize":3,
 "value":"abc",
 "encoding":"UTF-8",
 "references":[],
 "file":"irb/workspace.rb",
 "line":86,
 "method":"eval",
 "generation":15,
 "flags":{"wb_protected":true}
}

The heap dump produced by  ObjectSpace.dump_all can
be processed by the tool of your choice. You might try a  json processor like jq or a  json
database
 . Since the dump contains outbound references for each object, a full object graph can be re-created for deep analysis.

For example, here's a simple ruby/shell script to see which gems/libraries create the most long-lived objects of different types:

$ cat heap.json |
    ruby -rjson -ne ' puts JSON.parse($_).values_at("file","line","type").join(":") ' |
    sort        |
    uniq -c     |
    sort -n     |
    tail -4

26289 lib/active_support/dependencies.rb:184:NODE
29972 lib/active_support/dependencies.rb:184:DATA
43100 lib/psych/visitors/to_ruby.rb:324:STRING
47096 lib/active_support/dependencies.rb:184:STRING

If you have a ruby application that feels large or bloated, give these new ObjectSpace features a try. And if you end up writing a heap analysis tool  or visualization for these
json files, do let me know  on twitter .

Ruby 2.1: objspace.so的更多相关文章

  1. Ruby笔记

    1.数组遍历方法总结 array = (1..10).to_a length = array.length length.times do t print "#{array[t]} &quo ...

  2. 安装cocoapods遇到两大坑-Ruby版本升级和Podfile的配置

    今天安装cocoapods #移除原有ruby源 $ gem sources --remove https://rubygems.org/ #使用可用的淘宝网 $ gem sources -a htt ...

  3. Unable to download data from http://ruby.taobao.org/ & don't have write permissions for the /Library/Ruby/Gems/2.0.0 directory.

    安装cocoapods,记录两个问题! 1.镜像已经替换成了 http://ruby.taobao.org/, 还是不能不能安装cocoapods, 报错:Unable to download dat ...

  4. 安装了ruby后怎么安装sass

    在命令行中输入 ruby -v 查看版本号 先移除默认的https://rubygems.org源,命令为gem sources --remove https://rubygems.org/,按回车 ...

  5. ruby 基础知识(一)

    突然今天发现一大神的博客:http://www.cnblogs.com/jackluo/archive/2013/01/22/2871655.html    相信初学者会受益颇多 ruby  参考文档 ...

  6. ruby 基础知识(二)

    ruby  中的动态方法 http://singleant.iteye.com/blog/1680382 Rails 大量使用了符号(symbol).符号看上去很像变量名,不过以冒号作为前缀.符号的例 ...

  7. Ruby安装Scss

    Ruby安装Scss 引言 已经许久不写HTML了,今天有点以前的东西要改.但是刚装的Windows10,已经没有以前的Web开发环境了.只好重新安装. 结果Webstorm装好后配置Scss出现错误 ...

  8. fzf by ruby

    fzf by ruby */--> fzf by ruby 1 github地址 https://github.com/junegunn/fzf 2 简介 软件通过匿名管道和grep扩展了bas ...

  9. The Safe Navigation Operator (&.) in Ruby

    The most interesting addition to Ruby 2.3.0 is the Safe Navigation Operator(&.). A similar opera ...

随机推荐

  1. sql中InnoDB和MyISAM的区别

    InnoDB和MyISAM是许多人在使用MySQL时最常用的两个表类型 1,MyISAM类型的表强调的是性能,其执行数度比InnoDB类型更快,但是不提供事务支持等高级处理,往往被认为只适合小项目:而 ...

  2. android orm持久层框架

    ; ; i < 2; i++) { )); ); h1.setWord("这是修改过的数据"); tv.setText(tv.getText() + "\n&quo ...

  3. 一个简单的安卓+Servlet图片上传例子

    例子比较 简单,服务端为Java Web Servlet,doPost方法中接收图片并保存,然后将保存的图片名返回给客户端,关键代码: @SuppressWarnings("deprecat ...

  4. 压力测试工具Ab简介

    Apache安装包中自带的压力测试工具 Apache Benchmark(简称ab) 简单易用,这里就采用 ab作为压力测试工具了. 1.独立安装 通过 yum-utils中的yumdownload  ...

  5. Hibernate之持久化状态

    可持久化对象有以下三种状态: 临时状态(Transient):对象在保存进数据库之前为临时状态,这时数据库中没有该对象的信息,如果没有持久化,程序退出后临时状态的对象信息将会丢失.随时可能被垃圾回收器 ...

  6. UNIX网络编程——使用select函数的TCP和UDP回射服务器程序

    服务器程序: #include <sys/wait.h> #include <string.h> #include <string.h> #include < ...

  7. Java中封装性的使用

    //Java面对对象基本特性之一:封装性 //作用:保护某些属性和方法不被外部所看见 //封装的实现:通过关键字private声明 //鼠标右键--->Source---->Generat ...

  8. 【一天一道LeetCode】#108. Convert Sorted Array to Binary Search Tree

    一天一道LeetCode 本系列文章已全部上传至我的github,地址:ZeeCoder's Github 欢迎大家关注我的新浪微博,我的新浪微博 欢迎转载,转载请注明出处 (一)题目 Given a ...

  9. UNIX环境高级编程——信号之kill、raise、killpg、alarm、pause、abort、sleep、usleep、nanosleep和setitimer函数

    一.kill, raise, killpg 函数 int kill(pid_t pid, int sig); int raise(int sig); int killpg(int pgrp, int ...

  10. python安装json的方法;以及三种json库的区别

    python中的json解释库有好几个,不同版本使用方法不同. 常用有 json-py 与smiplejson 两个包 其中,json-py 包含json.py外,还有一个minjson,两者用法上有 ...