Created
October 5, 2016 12:13
-
-
Save spraints/da59eac1e92cd5bf104474bbf30254ac to your computer and use it in GitHub Desktop.
benchmark a few styles of constructors in ruby
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
# I wanted to see how fast different constructor styles were. | |
# | |
# Calculating ------------------------------------- | |
# splat 73.970k i/100ms | |
# manual splat 77.512k i/100ms | |
# kwarg 23.687k i/100ms | |
# attr 77.930k i/100ms | |
# opts 34.173k i/100ms | |
# fetch 29.289k i/100ms | |
# ------------------------------------------------- | |
# splat 1.912M (±21.2%) i/s - 8.950M | |
# manual splat 1.671M (±19.0%) i/s - 7.984M | |
# kwarg 268.841k (±41.2%) i/s - 1.066M | |
# attr 1.665M (±19.3%) i/s - 7.949M | |
# opts 439.918k (±48.4%) i/s - 1.674M | |
# fetch 374.149k (±50.0%) i/s - 1.347M | |
require "benchmark/ips" | |
class A | |
def initialize(a, b, c, d, e, f, g) | |
@a = a | |
@b = b | |
@c = c | |
@d = d | |
@e = e | |
@f = f | |
@g = g | |
end | |
end | |
class B | |
def initialize(a:, b:, c:, d:, e:, f:, g:) | |
@a = a | |
@b = b | |
@c = c | |
@d = d | |
@e = e | |
@f = f | |
@g = g | |
end | |
end | |
class C | |
attr_accessor :a, :b, :c, :d, :e, :f, :g | |
end | |
class D | |
def initialize(opts) | |
@a = opts[:a] | |
@b = opts[:b] | |
@c = opts[:c] | |
@d = opts[:d] | |
@e = opts[:e] | |
@f = opts[:f] | |
@g = opts[:g] | |
end | |
end | |
class E | |
def initialize(opts) | |
@a = opts.fetch(:a) | |
@b = opts.fetch(:b) | |
@c = opts.fetch(:c) | |
@d = opts.fetch(:d) | |
@e = opts.fetch(:e) | |
@f = opts.fetch(:f) | |
@g = opts.fetch(:g) | |
end | |
end | |
row = %w(a b c d e f g) | |
Benchmark.ips do |x| | |
x.report("splat") { |n| while n > 0; n -= 1; A.new(*row); end } | |
x.report("manual splat") { |n| while n > 0; n -= 1; A.new(row[0], row[1], row[2], row[3], row[4], row[5], row[6]); end } | |
x.report("kwarg") { |n| while n > 0; n -= 1; B.new(a: row[0], b: row[1], c: row[2], d: row[3], e: row[4], f: row[5], g: row[6]); end } | |
x.report("attr") { |n| while n > 0; n -= 1; c = C.new; c.a = row[0]; c.b = row[1]; c.c = row[2]; c.d = row[3]; c.e = row[4]; c.f = row[5]; c.g = row[6]; end } | |
x.report("opts") { |n| while n > 0; n -= 1; D.new(a: row[0], b: row[1], c: row[2], d: row[3], e: row[4], f: row[5], g: row[6]); end } | |
x.report("fetch") { |n| while n > 0; n -= 1; E.new(a: row[0], b: row[1], c: row[2], d: row[3], e: row[4], f: row[5], g: row[6]); end } | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment