Created
March 6, 2023 17:48
-
-
Save serradura/75cf89ce33b8c0004ca86510d3fc6a8f to your computer and use it in GitHub Desktop.
Benchmarks instance versus singleton methods
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
require 'bundler/inline' | |
gemfile do | |
source 'https://rubygems.org' | |
gem 'benchmark-ips', '~> 2.11' | |
end | |
class Calc | |
def initialize(a, b) | |
@a = a | |
@b = b | |
end | |
def add | |
@a + @b | |
end | |
end | |
module Calculator | |
def self.add(a, b) | |
a + b | |
end | |
end | |
Benchmark.ips do |x| | |
x.config(time: 5, warmup: 2) | |
x.report('instance') { Calc.new(1, 2).add; Calc.new(2, 3).add; Calc.new(4, 5).add; Calc.new(6, 7).add; Calc.new(8, 9).add } | |
x.report('singleton') { Calculator.add(1, 2); Calculator.add(2, 3); Calculator.add(4, 5); Calculator.add(6, 7); Calculator.add(8, 9) } | |
x.compare! | |
end | |
# Warming up -------------------------------------- | |
# instance 169.998k i/100ms | |
# singleton 620.519k i/100ms | |
# Calculating ------------------------------------- | |
# instance 1.698M (± 0.2%) i/s - 8.500M in 5.006098s | |
# singleton 6.220M (± 0.4%) i/s - 31.646M in 5.088116s | |
# Comparison: | |
# singleton: 6219791.8 i/s | |
# instance: 1697918.4 i/s - 3.66x slower |
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' | |
gemfile do | |
source 'https://rubygems.org' | |
gem 'benchmark-ips', '~> 2.11' | |
end | |
require 'net/https' | |
class DogPicFetcher | |
RANDOM = URI('https://dog.ceo/api/breeds/image/random') | |
def fetch = Net::HTTP.get(RANDOM) | |
end | |
module FetchDogPic | |
RANDOM = URI('https://dog.ceo/api/breeds/image/random') | |
def self.random = Net::HTTP.get(RANDOM) | |
end | |
Benchmark.ips do |x| | |
x.config(time: 5, warmup: 2) | |
x.report('instance') { DogPicFetcher.new.fetch } | |
x.report('singleton') { FetchDogPic.random } | |
x.compare! | |
end | |
# Warming up -------------------------------------- | |
# instance 1.000 i/100ms | |
# singleton 1.000 i/100ms | |
# Calculating ------------------------------------- | |
# instance 2.756 (±36.3%) i/s - 14.000 in 5.384464s | |
# singleton 3.562 (±28.1%) i/s - 17.000 in 5.147226s | |
# Comparison: | |
# singleton: 3.6 i/s | |
# instance: 2.8 i/s - same-ish: difference falls within error |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment