Last active
August 29, 2015 14:07
-
-
Save Asmod4n/ccb86462a727061801de to your computer and use it in GitHub Desktop.
Speed differences in FFI memory management
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
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