Last active
April 27, 2021 18:26
-
-
Save serradura/f3ccd4fbbe2af3bfe8f9b154871bd93e to your computer and use it in GitHub Desktop.
Async VS sync HTTP requests (using faraday and async.rb)
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 'faraday' | |
gem 'async-http-faraday' | |
gem 'pry' | |
end | |
require 'benchmark' | |
require 'async/http/faraday' | |
# Make it the global default: | |
Faraday.default_adapter = :async_http | |
# Per connection: | |
conn = Faraday.new(url: 'https://dog.ceo/') do |faraday| | |
faraday.adapter :async_http | |
end | |
result = [] | |
bench_result = Benchmark.measure do | |
Async do | |
response = conn.get("/api/breeds/list/all") | |
if response.status == 200 | |
breeds = JSON.parse(response.body)['message'].keys[0..9] | |
breeds.each do |breed| | |
Async do | |
breed_path = "/api/breed/#{breed}/images" | |
response = conn.get(breed_path) | |
p breed_path | |
result << JSON.parse(response.body) | |
end | |
end | |
end | |
end | |
end | |
puts bench_result | |
# result.flat_map { |i| i['message'] }.size | |
binding.pry | |
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 'faraday' | |
gem 'pry' | |
end | |
require 'benchmark' | |
require 'json' | |
# Make it the global default: | |
# Per connection: | |
conn = Faraday.new(url: 'https://dog.ceo/') | |
result = [] | |
bench_result = Benchmark.measure do | |
response = conn.get("/api/breeds/list/all") | |
if response.status == 200 | |
breeds = JSON.parse(response.body)['message'].keys[0..9] | |
breeds.each do |breed| | |
breed_path = "/api/breed/#{breed}/images" | |
response = conn.get(breed_path) | |
p breed_path | |
result << JSON.parse(response.body) | |
end | |
end | |
end | |
puts bench_result | |
# result.flat_map { |i| i['message'] }.size | |
binding.pry |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment