Created
December 28, 2009 15:17
-
-
Save EmmanuelOga/264718 to your computer and use it in GitHub Desktop.
Hash vs Struct allocations test
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Use with ree. | |
# http://blog.evanweaver.com/articles/2009/10/21/object-allocations-on-the-web/ | |
GC.enable_stats | |
def sizeof(obj) | |
GC.clear_stats | |
obj.clone | |
puts "#{GC.num_allocations} allocations" | |
GC.clear_stats | |
obj.clone | |
puts "#{GC.allocated_size} bytes" | |
end | |
h = { | |
:url => "http://someurl.com/somewhere/else", | |
:proxy_url => "x" * 120, | |
:body_data => "x" * 120, | |
:body_proc => "x" * 120, | |
:header_data => "x" * 120, | |
:header_proc => "x" * 120, | |
:progress_proc => "x" * 120, | |
:debug_proc => "x" * 120, | |
:interface_hm => "x" * 120, | |
:userpwd => "x" * 120, | |
:username => "x" * 120, | |
:password => "x" * 120, | |
:proxypwd => "x" * 120, | |
:headers => ('a'..'z').inject({}) {|h,k| h[k * 10] = k * 100; h}, | |
:cookies => "x" * 120, | |
:cookiefile => "x" * 120, | |
:cookiejar => "x" * 120, | |
:cert => "x" * 120, | |
:cacert => "x" * 120, | |
:certpassword => "x" * 120, | |
:certtype => "PEM" * 1024, | |
:encoding => "x" * 120, | |
:useragent => "x" * 120, | |
:success_proc => "x" * 120, | |
:failure_proc => "x" * 120, | |
:complete_proc => "x" * 120 | |
} | |
puts "With an empty Hash instance: " | |
sizeof(Hash.new); | |
puts "With a Hash instance, only url and headers: " | |
sizeof({ :url => "http://someurl.com/somewhere/else", :headers => { :user => "E", :password => "123456788" }}); | |
puts "With a populated Hash instance: " | |
sizeof(h); | |
S = Struct.new *h.keys | |
puts "With an empty Struct instance: " | |
sizeof(S.new); | |
s = S.new | |
h.each do |k,v| | |
s.send("#{ k }=", v) | |
end | |
puts "With a populated Struct instance: " | |
sizeof(s); | |
__END__ | |
With an empty Hash instance: | |
2 allocations | |
112 bytes | |
With a Hash instance, only url and headers: | |
4 allocations | |
176 bytes | |
With a populated Hash instance: | |
28 allocations | |
944 bytes | |
With an empty Struct instance: | |
1 allocations | |
208 bytes | |
With a populated Struct instance: | |
1 allocations | |
208 bytes |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment