SlideShare une entreprise Scribd logo
1  sur  21
Code Optimizations Ruby 1 28 minutes
Huh? What’s that? 2
Why would I want to do that? Money Resources Hardware People (Developers) Time Speed of operation Developer takes to figure out what’s going on Karma No one wants to write bad code! 3
4 Ruby
Interpolation over Concatenation puts "This string embeds #{a} and #{b} through interpolation"# => faster puts "This string concatenates "<< a <<" and "<< b  # => slower puts "This string concatenates “+ a +" and "+ b  # => slower 5
Destructive Operations! hash = {} hash =hash.merge({1=>2})  # duplicates the original hash hash.merge!({1=>2})  # equivalent to previous line, and faster str="string to gsub" str=str.gsub(/to/, 'copy')  # duplicate string and reassigns it str.gsub!(/to/, 'copy')  # same effect, but no object duplication 6
Benchmark everything require 'benchmark' n =100000 Benchmark.bm do |x|  x.report('copy') { n.timesdo ; h = {}; h =h.merge({1=>2}); end }    x.report('no copy') { n.timesdo ; h = {}; h.merge!({1=>2}); end } end #          user       system     total       real # copy    0.460000   0.180000   0.640000  (0.640692) # no copy 0.340000   0.120000   0.460000  (0.463339) 7
Symbols whenever possible 'foo'.object_id# => 23233310 'foo'.object_id# => 23228920 :foo.object_id# => 239298 :foo.object_id# => 239298 8
Array joins [1, 2, 3] * 3 # => [1, 2, 3, 1, 2, 3, 1, 2, 3] [1, 2, 3] * '3'# => "13233"  %w{thisisatest} * ", " # => "this, is, a, test"  h = { :name=>"Fred", :age=>77 } h.map { |i| i * "=" } * "" # => "age=77name=Fred" 9
Everything is an object! defadd(adder, addee)   adder +addee end  add(3,5) # => 8 classFixnum defadd(num) self+ num end end 3.add(5)# => 8 10
Use ranges instead of complex comparisons for numbers # No more if x > 1000 && x < 2000 nonsense. Instead: year =1972 puts  case year when1970..1979:"Seventies" when1980..1989:"Eighties" when1990..1999:"Nineties" end 11
Ruby logic defis_odd(x)     if x % 2==0 returnfalse else returntrue end end defis_odd(x)   x % 2==0?false:true end defis_odd(x)   x % 2!=0 end 12 classFixnum def odd? self % 2!=0 end end 2.odd? # => false
Enumerate single object # [*items] converts a single object into an array. And if the object is an array, keeps it as it is. [*items].each do |item| # ... end 13
14 Rails
Caching Page Caching Fragment Caching Action Caching Caching into Local / Instance Variable 15 # Makes a database query only if @current_user is nil defcurrent_user @current_user||=User.find(session[:user_id]) end
Don’t limit yourself to ActiveRecord Use performance boosting database  features like:  Stored procedures Functions X-query 16
Finders are great but be careful Retrieve only the information that you need.  Don’t kill your database with too many queries. Use eager loading. Avoid dynamic finders like MyModel.find_by_*. Need an optimized query? Run MyModel.find_by_sql. 17 #This will generates only one query, # rather than Post.count + 1 queries for post inPost.find(:all, :include=> [ :author, :comments ]) # Do something with post end
Control your controllers Don’t let them become the God classes. Lesser instance variables. Slimmer the better. Appropriate code in appropriate controller. 18
19 And of course!
20 Obey design principles. Always code in context (Objects). It is the best way to model your solution. Avoid “Quick and dirty”. Understand that no good can ever come out of duplication. Be it code, design, data and most importantly effort. Simplicity is the key. Enjoy coding!
21 Slides slideshare.net/ihower/rails-best-practices slideshare.net/ihower/practical-rails2-350619 slideshare.net/preston.lee/logical-programming-with-ruby-prolog Ruby Books The Ruby Wayby Hal Edwin Fulton, Guy Hurst The Rails Way by Obie Fernandez Design Patterns in Rubyby Russ Olsen Software Construction Code Complete 2 by Steve McConnell The Pragmatic Programmer: From Journeyman to Masterby Andrew Hunt

Contenu connexe

Tendances

Rust: код может быть одновременно безопасным и быстрым, Степан Кольцов
Rust: код может быть одновременно безопасным и быстрым, Степан КольцовRust: код может быть одновременно безопасным и быстрым, Степан Кольцов
Rust: код может быть одновременно безопасным и быстрым, Степан Кольцов
Yandex
 
Devoxx UK 2014 High Performance In-Memory Java with Open Source
Devoxx UK 2014   High Performance In-Memory Java with Open SourceDevoxx UK 2014   High Performance In-Memory Java with Open Source
Devoxx UK 2014 High Performance In-Memory Java with Open Source
Hazelcast
 
Степан Кольцов — Rust — лучше, чем C++
Степан Кольцов — Rust — лучше, чем C++Степан Кольцов — Rust — лучше, чем C++
Степан Кольцов — Rust — лучше, чем C++
Yandex
 
An Introduction to JavaScript: Week 5
An Introduction to JavaScript: Week 5An Introduction to JavaScript: Week 5
An Introduction to JavaScript: Week 5
Event Handler
 

Tendances (11)

A Spin-off: Firebird Checked by PVS-Studio
A Spin-off: Firebird Checked by PVS-StudioA Spin-off: Firebird Checked by PVS-Studio
A Spin-off: Firebird Checked by PVS-Studio
 
Random numbers c++ class 11 and 12
Random numbers c++  class 11 and 12Random numbers c++  class 11 and 12
Random numbers c++ class 11 and 12
 
Introduction to Vim
Introduction to VimIntroduction to Vim
Introduction to Vim
 
.Net 4.0 Threading and Parallel Programming
.Net 4.0 Threading and Parallel Programming.Net 4.0 Threading and Parallel Programming
.Net 4.0 Threading and Parallel Programming
 
Lecture 3
Lecture 3Lecture 3
Lecture 3
 
Rust Synchronization Primitives
Rust Synchronization PrimitivesRust Synchronization Primitives
Rust Synchronization Primitives
 
Rust: код может быть одновременно безопасным и быстрым, Степан Кольцов
Rust: код может быть одновременно безопасным и быстрым, Степан КольцовRust: код может быть одновременно безопасным и быстрым, Степан Кольцов
Rust: код может быть одновременно безопасным и быстрым, Степан Кольцов
 
git session --interactive
git session --interactivegit session --interactive
git session --interactive
 
Devoxx UK 2014 High Performance In-Memory Java with Open Source
Devoxx UK 2014   High Performance In-Memory Java with Open SourceDevoxx UK 2014   High Performance In-Memory Java with Open Source
Devoxx UK 2014 High Performance In-Memory Java with Open Source
 
Степан Кольцов — Rust — лучше, чем C++
Степан Кольцов — Rust — лучше, чем C++Степан Кольцов — Rust — лучше, чем C++
Степан Кольцов — Rust — лучше, чем C++
 
An Introduction to JavaScript: Week 5
An Introduction to JavaScript: Week 5An Introduction to JavaScript: Week 5
An Introduction to JavaScript: Week 5
 

Similaire à Ruby Code Optimizations (for beginners)

Beware: Sharp Tools
Beware: Sharp ToolsBeware: Sharp Tools
Beware: Sharp Tools
chrismdp
 
Modify this code to use multiple threads with the same data1.Modif.pdf
Modify this code to use multiple threads with the same data1.Modif.pdfModify this code to use multiple threads with the same data1.Modif.pdf
Modify this code to use multiple threads with the same data1.Modif.pdf
mallik3000
 
Uses & Abuses of Mocks & Stubs
Uses & Abuses of Mocks & StubsUses & Abuses of Mocks & Stubs
Uses & Abuses of Mocks & Stubs
PatchSpace Ltd
 
Rapid Development with Ruby/JRuby and Rails
Rapid Development with Ruby/JRuby and RailsRapid Development with Ruby/JRuby and Rails
Rapid Development with Ruby/JRuby and Rails
elliando dias
 

Similaire à Ruby Code Optimizations (for beginners) (20)

PostgreSQL as seen by Rubyists (Kaigi on Rails 2022)
PostgreSQL as seen by Rubyists (Kaigi on Rails 2022)PostgreSQL as seen by Rubyists (Kaigi on Rails 2022)
PostgreSQL as seen by Rubyists (Kaigi on Rails 2022)
 
Ruby Topic Maps Tutorial (2007-10-10)
Ruby Topic Maps Tutorial (2007-10-10)Ruby Topic Maps Tutorial (2007-10-10)
Ruby Topic Maps Tutorial (2007-10-10)
 
Scala 3camp 2011
Scala   3camp 2011Scala   3camp 2011
Scala 3camp 2011
 
Ruby presentasjon på NTNU 22 april 2009
Ruby presentasjon på NTNU 22 april 2009Ruby presentasjon på NTNU 22 april 2009
Ruby presentasjon på NTNU 22 april 2009
 
Ruby presentasjon på NTNU 22 april 2009
Ruby presentasjon på NTNU 22 april 2009Ruby presentasjon på NTNU 22 april 2009
Ruby presentasjon på NTNU 22 april 2009
 
Ruby presentasjon på NTNU 22 april 2009
Ruby presentasjon på NTNU 22 april 2009Ruby presentasjon på NTNU 22 april 2009
Ruby presentasjon på NTNU 22 april 2009
 
Method::Signatures
Method::SignaturesMethod::Signatures
Method::Signatures
 
Async and Parallel F#
Async and Parallel F#Async and Parallel F#
Async and Parallel F#
 
Async and Parallel F#
Async and Parallel F#Async and Parallel F#
Async and Parallel F#
 
Beware: Sharp Tools
Beware: Sharp ToolsBeware: Sharp Tools
Beware: Sharp Tools
 
Making JavaScript Libraries More Approachable
Making JavaScript Libraries More ApproachableMaking JavaScript Libraries More Approachable
Making JavaScript Libraries More Approachable
 
No Callbacks, No Threads - RailsConf 2010
No Callbacks, No Threads - RailsConf 2010No Callbacks, No Threads - RailsConf 2010
No Callbacks, No Threads - RailsConf 2010
 
Impacta - Show Day de Rails
Impacta - Show Day de RailsImpacta - Show Day de Rails
Impacta - Show Day de Rails
 
Ruby on Rails 3.1: Let's bring the fun back into web programing
Ruby on Rails 3.1: Let's bring the fun back into web programingRuby on Rails 3.1: Let's bring the fun back into web programing
Ruby on Rails 3.1: Let's bring the fun back into web programing
 
Modify this code to use multiple threads with the same data1.Modif.pdf
Modify this code to use multiple threads with the same data1.Modif.pdfModify this code to use multiple threads with the same data1.Modif.pdf
Modify this code to use multiple threads with the same data1.Modif.pdf
 
A Toda Maquina Con Ruby on Rails
A Toda Maquina Con Ruby on RailsA Toda Maquina Con Ruby on Rails
A Toda Maquina Con Ruby on Rails
 
Uses & Abuses of Mocks & Stubs
Uses & Abuses of Mocks & StubsUses & Abuses of Mocks & Stubs
Uses & Abuses of Mocks & Stubs
 
Rapid Development with Ruby/JRuby and Rails
Rapid Development with Ruby/JRuby and RailsRapid Development with Ruby/JRuby and Rails
Rapid Development with Ruby/JRuby and Rails
 
C++11 - A Change in Style - v2.0
C++11 - A Change in Style - v2.0C++11 - A Change in Style - v2.0
C++11 - A Change in Style - v2.0
 
My First Rails Plugin - Usertext
My First Rails Plugin - UsertextMy First Rails Plugin - Usertext
My First Rails Plugin - Usertext
 

Dernier

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Dernier (20)

Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
A Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusA Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source Milvus
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 

Ruby Code Optimizations (for beginners)

  • 1. Code Optimizations Ruby 1 28 minutes
  • 3. Why would I want to do that? Money Resources Hardware People (Developers) Time Speed of operation Developer takes to figure out what’s going on Karma No one wants to write bad code! 3
  • 5. Interpolation over Concatenation puts "This string embeds #{a} and #{b} through interpolation"# => faster puts "This string concatenates "<< a <<" and "<< b # => slower puts "This string concatenates “+ a +" and "+ b # => slower 5
  • 6. Destructive Operations! hash = {} hash =hash.merge({1=>2}) # duplicates the original hash hash.merge!({1=>2}) # equivalent to previous line, and faster str="string to gsub" str=str.gsub(/to/, 'copy') # duplicate string and reassigns it str.gsub!(/to/, 'copy') # same effect, but no object duplication 6
  • 7. Benchmark everything require 'benchmark' n =100000 Benchmark.bm do |x| x.report('copy') { n.timesdo ; h = {}; h =h.merge({1=>2}); end } x.report('no copy') { n.timesdo ; h = {}; h.merge!({1=>2}); end } end # user system total real # copy 0.460000 0.180000 0.640000 (0.640692) # no copy 0.340000 0.120000 0.460000 (0.463339) 7
  • 8. Symbols whenever possible 'foo'.object_id# => 23233310 'foo'.object_id# => 23228920 :foo.object_id# => 239298 :foo.object_id# => 239298 8
  • 9. Array joins [1, 2, 3] * 3 # => [1, 2, 3, 1, 2, 3, 1, 2, 3] [1, 2, 3] * '3'# => "13233"  %w{thisisatest} * ", " # => "this, is, a, test"  h = { :name=>"Fred", :age=>77 } h.map { |i| i * "=" } * "" # => "age=77name=Fred" 9
  • 10. Everything is an object! defadd(adder, addee) adder +addee end  add(3,5) # => 8 classFixnum defadd(num) self+ num end end 3.add(5)# => 8 10
  • 11. Use ranges instead of complex comparisons for numbers # No more if x > 1000 && x < 2000 nonsense. Instead: year =1972 puts case year when1970..1979:"Seventies" when1980..1989:"Eighties" when1990..1999:"Nineties" end 11
  • 12. Ruby logic defis_odd(x) if x % 2==0 returnfalse else returntrue end end defis_odd(x) x % 2==0?false:true end defis_odd(x) x % 2!=0 end 12 classFixnum def odd? self % 2!=0 end end 2.odd? # => false
  • 13. Enumerate single object # [*items] converts a single object into an array. And if the object is an array, keeps it as it is. [*items].each do |item| # ... end 13
  • 15. Caching Page Caching Fragment Caching Action Caching Caching into Local / Instance Variable 15 # Makes a database query only if @current_user is nil defcurrent_user @current_user||=User.find(session[:user_id]) end
  • 16. Don’t limit yourself to ActiveRecord Use performance boosting database features like: Stored procedures Functions X-query 16
  • 17. Finders are great but be careful Retrieve only the information that you need.  Don’t kill your database with too many queries. Use eager loading. Avoid dynamic finders like MyModel.find_by_*. Need an optimized query? Run MyModel.find_by_sql. 17 #This will generates only one query, # rather than Post.count + 1 queries for post inPost.find(:all, :include=> [ :author, :comments ]) # Do something with post end
  • 18. Control your controllers Don’t let them become the God classes. Lesser instance variables. Slimmer the better. Appropriate code in appropriate controller. 18
  • 19. 19 And of course!
  • 20. 20 Obey design principles. Always code in context (Objects). It is the best way to model your solution. Avoid “Quick and dirty”. Understand that no good can ever come out of duplication. Be it code, design, data and most importantly effort. Simplicity is the key. Enjoy coding!
  • 21. 21 Slides slideshare.net/ihower/rails-best-practices slideshare.net/ihower/practical-rails2-350619 slideshare.net/preston.lee/logical-programming-with-ruby-prolog Ruby Books The Ruby Wayby Hal Edwin Fulton, Guy Hurst The Rails Way by Obie Fernandez Design Patterns in Rubyby Russ Olsen Software Construction Code Complete 2 by Steve McConnell The Pragmatic Programmer: From Journeyman to Masterby Andrew Hunt