Created
June 28, 2022 10:38
-
-
Save Bodacious/6472ccc3cbf8b98b573a292790dfa82f to your computer and use it in GitHub Desktop.
Jbuilder named attributes vs `extract!`
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 | |
gem "benchmark-ips" | |
gem "jbuilder" | |
gem "activesupport", require: ["active_support"] | |
end | |
class User | |
attr_accessor :id, :name, :email, :password, :age, :username | |
def initialize(attributes={}) | |
attributes.each do |key, value| | |
instance_variable_set("@#{key}", value) | |
end | |
end | |
end | |
user = User.new({ | |
id: 1, | |
name: "User name", | |
username: "username", | |
email: "User email", | |
password: "User password", | |
age: 50, | |
}) | |
Benchmark.ips do |test| | |
test.report("named") do | |
Jbuilder.new do |json| | |
json.id user.id | |
json.name user.name | |
json.username user.username | |
json.email user.email | |
json.password user.password | |
json.age user.age | |
end.target! | |
end | |
test.report(".extract!") do | |
Jbuilder.new do |json| | |
json.(user, :id, :name, :username, :email, :password, :age) | |
end.target! | |
end | |
end |
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
Warming up -------------------------------------- | |
named 12.273k i/100ms | |
.extract! 14.050k i/100ms | |
Calculating ------------------------------------- | |
named 129.049k (± 2.5%) i/s - 650.469k in 5.043950s | |
.extract! 142.074k (± 2.1%) i/s - 716.550k in 5.045696s |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment