Skip to content

Instantly share code, notes, and snippets.

@jgaskins
Created December 3, 2020 04:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jgaskins/dc347dfa62f275a4c9563db90b900f12 to your computer and use it in GitHub Desktop.
Save jgaskins/dc347dfa62f275a4c9563db90b900f12 to your computer and use it in GitHub Desktop.
Benchmarking allocation time of Crystal objects with various quantities of instance variables
require "benchmark"
value = nil
Benchmark.ips do |x|
x.report "1 ivar" { value = OneIVar.new }
x.report "2 ivars" { value = TwoIVars.new }
x.report "4 ivars" { value = FourIVars.new }
x.report "8 ivars" { value = EightIVars.new }
x.report "16 ivars" { value = SixteenIVars.new }
end
pp value
class OneIVar
@var1 = "foo"
end
class TwoIVars
@var1 = "foo"
@var2 = "foo"
end
class FourIVars
@var1 = "foo"
@var2 = "foo"
@var3 = "foo"
@var4 = "foo"
end
class EightIVars
@var1 = "foo"
@var2 = "foo"
@var3 = "foo"
@var4 = "foo"
@var5 = "foo"
@var6 = "foo"
@var7 = "foo"
@var8 = "foo"
end
class SixteenIVars
@var1 = "foo"
@var2 = "foo"
@var3 = "foo"
@var4 = "foo"
@var5 = "foo"
@var6 = "foo"
@var7 = "foo"
@var8 = "foo"
@var9 = "foo"
@var10 = "foo"
@var11 = "foo"
@var12 = "foo"
@var13 = "foo"
@var14 = "foo"
@var15 = "foo"
@var16 = "foo"
end
$ crystal run --release bench_allocations.cr
1 ivar 67.35M ( 14.85ns) (± 1.10%) 32.0B/op fastest
2 ivars 66.60M ( 15.01ns) (± 0.99%) 32.0B/op 1.01× slower
4 ivars 52.89M ( 18.91ns) (± 1.01%) 48.0B/op 1.27× slower
8 ivars 36.03M ( 27.75ns) (± 1.14%) 80.0B/op 1.87× slower
16 ivars 21.68M ( 46.12ns) (± 1.05%) 144B/op 3.11× slower
@straight-shoota
Copy link

s/class/struct/g/ yields equivalent measurements:

 1 ivar 571.66M (  1.75ns) (±14.32%)  0.0B/op        fastest
 2 ivars 505.86M (  1.98ns) (± 9.52%)  0.0B/op   1.13× slower
 4 ivars 500.13M (  2.00ns) (±10.77%)  0.0B/op   1.14× slower
 8 ivars 349.30M (  2.86ns) (±10.59%)  0.0B/op   1.64× slower
16 ivars 192.03M (  5.21ns) (± 9.80%)  0.0B/op   2.98× slower

So this benchmark does not reliably represent a difference based on allocation time.

@jgaskins
Copy link
Author

jgaskins commented Dec 3, 2020

Oh interesting! 👍🏼

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment