Skip to content

Instantly share code, notes, and snippets.

@jemc
Forked from Asmod4n/speed_test.rb
Created January 27, 2015 19:27
Show Gist options
  • Save jemc/6d6e86e4f455220f8c00 to your computer and use it in GitHub Desktop.
Save jemc/6d6e86e4f455220f8c00 to your computer and use it in GitHub Desktop.
require 'ffi'
require 'benchmark'
module LibC
extend FFI::Library
ffi_lib FFI::Library::LIBC
attach_function :malloc, [:size_t], :pointer
attach_function :free, [:pointer], :void
end
class ManagedObj
def initialize
@obj = LibC.malloc(500)
ObjectSpace.define_finalizer(@obj, self.class.free(@obj.address))
end
def free
ObjectSpace.undefine_finalizer @obj
LibC.free(@obj)
end
def self.free(address)
->(obj_id) { LibC.free(FFI::Pointer.new(address)) }
end
end
class ManualDealloc
def initialize
@obj = LibC.malloc(500)
end
def free
LibC.free(@obj)
end
end
puts 'MemoryPointer'
10.times { puts Benchmark.measure { 100000.times { FFI::MemoryPointer.new(500) } } }
puts 'ManagedObj'
10.times { puts Benchmark.measure { 100000.times { ManagedObj.new } } }
puts 'manual deallocation'
10.times { puts Benchmark.measure { 100000.times { ManualDealloc.new.free } } }
puts 'Unmanaged'
10.times { puts Benchmark.measure { 100000.times { LibC.free(LibC.malloc(500)) } } }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment