Skip to content

Instantly share code, notes, and snippets.

@adelahayepm
Last active April 8, 2021 07:18
Show Gist options
  • Save adelahayepm/00dedabd1cd83ef67be1996d2f8e9197 to your computer and use it in GitHub Desktop.
Save adelahayepm/00dedabd1cd83ef67be1996d2f8e9197 to your computer and use it in GitHub Desktop.
Benchmark HTTParty vs HTTP.rb with sample API fetching
require 'benchmark'
require 'httparty'
require 'http'
puts '------------- HTTParty ---------------'
time = Benchmark.measure do
class ChuckNorrisIO
attr_writer :category
include HTTParty
base_uri 'api.chucknorris.io'
def random_joke
self.class.get('/jokes/random', options)
end
def categories
self.class.get('/jokes/categories')
end
def options
{
category: @category
}.compact
end
end
chuck = ChuckNorrisIO.new
categ = chuck.categories.sample
p categ
chuck.category = categ
3.times { p chuck.random_joke['value'] }
end
puts time
puts '------------- HTTP.rb ---------------'
time = Benchmark.measure do
class ChuckNorrisIO2
attr_accessor :category
def random_joke
resp = client.get('/jokes/random', params: options)
resp.parse(:json) if resp.status.success?
end
def categories
resp = client.get('/jokes/categories')
resp.parse(:json) if resp.status.success?
end
def client
@client ||= build_client
end
def options
{
category: @category
}.compact
end
private
def build_client
@client = HTTP.persistent 'https://api.chucknorris.io'
end
end
chuck2 = ChuckNorrisIO2.new
categ = chuck2.categories.sample
p categ
chuck2.category = categ
3.times { p chuck2.random_joke['value'] }
end
puts time
source 'https://rubygems.org'
gem 'httparty'
gem 'http'
------------- HTTParty ---------------
"food"
"Chuck Norris was in Terminator 2. He was Judgement Day."
"Chuck Norris has never had to start back at 'square one'. If he ever messes up, he'll start back at octagon fifty-two."
"Chuck Norris turned down the role of Han Solo's father."
0.049189 0.004707 0.053896 ( 1.062062)
------------- HTTP.rb ---------------
"science"
"Science Fact: Roundhouse kicks are comprised primarily of an element called Chucktanium."
"The easiest way to determine Chuck Norris' age is to cut him in half and count the rings."
"Chuck Norris knows the last digit of pi."
0.017910 0.003547 0.021457 ( 0.461541)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment