Created
April 14, 2020 06:07
-
-
Save elct9620/afd3743da3a61dde699825dd092a4144 to your computer and use it in GitHub Desktop.
Ruby's Struct and Class benchmark (bemchmark-ips)
This file contains hidden or 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
# frozen_string_literal: true | |
require 'bundler/inline' | |
require 'ostruct' | |
gemfile do | |
gem 'benchmark-ips' | |
end | |
GeoStruct = Struct.new(:latitude, :longitude) do | |
def pair | |
[latitude, longitude] | |
end | |
end | |
# :nodoc: | |
class GeoClass | |
attr_reader :latitude, :longitude | |
def initialize(latitude, longitude) | |
@latitude = latitude | |
@longitude = longitude | |
end | |
def to_a | |
[@latitude, @longitude] | |
end | |
end | |
# :nodoc: | |
class GCSuite | |
def warming(*) | |
run_gc | |
end | |
def running(*) | |
run_gc | |
end | |
def warmup_stats(*); end | |
def add_report(*); end | |
private | |
def run_gc | |
GC.enable | |
GC.start | |
GC.start | |
GC.start | |
GC.disable | |
end | |
end | |
suite = GCSuite.new | |
def challenge_new(bm) | |
bm.report('GeoStruct.new') { GeoStruct.new(11.1, 12.1) } | |
bm.report('GeoClass.new') { GeoClass.new(11.1, 12.1) } | |
end | |
def challenge_access(bm) | |
geo_s = GeoStruct.new(11.1, 12.1) | |
geo_c = GeoClass.new(11.1, 12.1) | |
bm.report('GeoStruct#to_a') do | |
geo_s.to_a | |
end | |
bm.report('GeoStruct#pair') do | |
geo_s.to_a | |
end | |
bm.report('GeoClass#to_a') do | |
geo_c.to_a | |
end | |
end | |
def challenge_attr(bm) | |
geo_s = GeoStruct.new(11.1, 12.1) | |
geo_c = GeoClass.new(11.1, 12.1) | |
bm.report('GeoStruct#latitude') { geo_s.latitude } | |
bm.report('GeoClass#to_a') { geo_c.latitude } | |
end | |
puts '=== New without GC ===' | |
Benchmark.ips do |bm| | |
bm.config(suite: suite) | |
challenge_new(bm) | |
end | |
puts '=== New with GC ===' | |
Benchmark.ips do |bm| | |
challenge_new(bm) | |
end | |
puts '=== To Array without GC ===' | |
Benchmark.ips do |bm| | |
bm.config(suite: suite) | |
challenge_access(bm) | |
end | |
puts '=== To Array with GC ===' | |
Benchmark.ips do |bm| | |
challenge_access(bm) | |
end | |
puts '=== Get attribute without GC ===' | |
Benchmark.ips do |bm| | |
bm.config(suite: suite) | |
challenge_attr(bm) | |
end | |
puts '=== Get attribute Array with GC ===' | |
Benchmark.ips do |bm| | |
challenge_attr(bm) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Ruby 2.7.0