Skip to content

Instantly share code, notes, and snippets.

@kerrizor
Last active February 17, 2016 16:52
Show Gist options
  • Save kerrizor/e961504d1fbd425bfe97 to your computer and use it in GitHub Desktop.
Save kerrizor/e961504d1fbd425bfe97 to your computer and use it in GitHub Desktop.
Structs vs Classes vs Classes-That-Inherit-From-Structs
require 'ostruct'
require 'benchmark'

ITERATIONS = 10_000_000
FOO        = "Bar"
BAZ        = "Bat"

NewStruct = Struct.new(:foo, :bar)

class Thingie
  attr_accessor :foo, :bar
end

class ThingieStruct < Struct.new(:foo, :bar)
  attr_accessor :foo, :bar
end

Benchmark.bm(8) do |b|
  b.report("struct:") do
    ITERATIONS.times do
      p = NewStruct.new
      p.foo = FOO
      p.bar = BAZ
    end
  end

  b.report("class:") do
    ITERATIONS.times do
      p = Thingie.new
      p.foo = FOO
      p.bar = BAZ
    end
  end

  b.report("struct-class:") do
    ITERATIONS.times do
      p = ThingieStruct.new
      p.foo = FOO
      p.bar = BAZ
    end
  end
end
                   user     system      total        real
struct:        2.540000   0.000000   2.540000 (  2.546056)
class:         1.740000   0.010000   1.750000 (  1.748066)
struct-class:  8.490000   0.130000   8.620000 (  8.629484)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment