On Fri, May 21, 2010 at 1:35 AM, timr <timrandg / gmail.com> wrote:

> I was playing around looking at ObjectSpace in irb and was astounded
> at how many string objects there are. Why are there 57,000+ String
> objects?!?
>
> hash = {}
> ObjectSpace.each_object.collect{|t| t.class}.uniq.each{|cla| hash[cla]
> = ObjectSpace.each_object(cla).to_a.length}
> hash
>
> {Tiger=>1, Gem::SourceIndex=>1, Gem::Version=>601, String=>57656,
> RubyToken::TkNL=>1, Gem::Dependency=>206, Proc=>127, NoMemoryError=>1,
> UnboundMethod=>1, IRB::WorkSpace=>1, Rational=>10, Mutex=>1,
> Thread=>1, IO=>5, Object=>64965, Binding=>3, Array=>3761, Float=>18,
> OptionParser::Switch::NoArgument=>2,
> IRB::Notifier::CompositeNotifier=>1, Range=>51, Bignum=>2, fatal=>1,
> OptionParser::OptionMap=>2, Gem::CommandManager=>1, IRB::Locale=>1,
> RubyLex::TerminateLineInput=>1, Date::Infinity=>2,
> Gem::Requirement=>554, SystemStackError=>1, Module=>495, Hash=>130,
> YAML::Syck::Resolver=>2, ThreadGroup=>1, Gem::Specification=>173,
> IRB::SLex=>1, Gem::GemPathSearcher=>1, File=>2, Class=>438,
> IRB::Notifier::LeveledNotifier=>4, RubyToken::TkLPAREN=>1,
> OptionParser::List=>1, OptionParser::CompletingHash=>1,
> RubyToken::TkRBRACE=>1, Enumerable::Enumerator=>10, Method=>1,
> IRB::ReadlineInputMethod=>1, IRB::StdioOutputMethod=>2, RubyLex=>1,
> IRB::SLex::Node=>78, Gem::ConfigFile=>1, MatchData=>4,
> IRB::Context=>1, Regexp=>353, IRB::Notifier::NoMsgNotifier=>1,
> IRB::Irb=>1, Gem::Version::Part=>481, Time=>176}
>
>
> And if I do:
>
> ObjectSpace.each_object(String).each{|str| hash[str.object_id] = str}
>
> I find that most of these strings appear to be paths to ruby files. I
> am curious if everyone has a similarly large set of string objects in
> their ObjectSpace, or is this a result of my personalized setup?
>
>
Using your code, in irb:
MRI 1.8.7 => 36715
MRI 1.9.1 => 3752
Rubinius 1.0 => 4797
MacRuby 0.6 => 3013

And your code didn't work in JRuby 1.5.0, or MRI 1.8.6


However, outside of irb, using
ruby -e "hash = {} ; ObjectSpace.each_object.collect{|t|
t.class}.uniq.each{|cla| hash[cla] =
ObjectSpace.each_object(cla).to_a.length} ; p hash[String]"

I got:
MRI 1.8.7 => 126
MRI 1.9.1 => 1708
Rubinius 1.0 => 3424
MacRuby 0.6 => 1120