Skip to content

Instantly share code, notes, and snippets.

View jonas-schulze's full-sized avatar

Jonas Schulze jonas-schulze

  • Max Planck Institute for Dynamics of Complex Technical Systems
  • Magdeburg, Germany
  • 11:59 (UTC +02:00)
View GitHub Profile
@jonas-schulze
jonas-schulze / do_not_use_exceptions_for_control_flow.rb
Last active March 15, 2018 10:18
Ruby Performance Tricks -- 6 Years Later -- Trick 1
require 'benchmark'
class Obj
def with_condition
respond_to?(:mythical_method) ? self.mythical_method : nil
end
def with_rescue
self.mythical_method
rescue NoMethodError
@jonas-schulze
jonas-schulze / prefer_shift_over_pluseq_for_string_concatenation.rb
Last active March 15, 2018 11:03
Ruby Performance Tricks -- 6 Years Later -- Trick 2
require 'benchmark'
N = 1000
BASIC_LENGTH = 10
puts RUBY_DESCRIPTION
5.times do |factor|
length = BASIC_LENGTH * (10 ** factor)
puts "_" * 60 + "\nLENGTH: #{length}"
@jonas-schulze
jonas-schulze / be_careful_with_calculations_within_iterators.rb
Last active March 15, 2018 11:03
Ruby Performance Tricks -- 6 Years Later -- Trick 3
require 'benchmark'
def n_func(array)
array.inject({}) { |h, e| h[e] = e; h }
end
def n2_func(array)
array.inject({}) { |h, e| h.merge(e => e) }
end
@jonas-schulze
jonas-schulze / use_instance_variables.rb
Created March 15, 2018 11:18
Ruby Performance Tricks -- 6 Years Later -- Trick 5
require 'benchmark'
class Metric
attr_accessor :var
def initialize(n)
@n = n
@var = 22
end
@jonas-schulze
jonas-schulze / avoid_parallel_assignment.rb
Created March 15, 2018 11:20
Ruby Performance Tricks -- 6 Years Later -- Trick 6
require 'benchmark'
N = 10_000_000
puts RUBY_DESCRIPTION
Benchmark.bm(15) do |x|
x.report('parallel') do
N.times do
a, b = 10, 20
@jonas-schulze
jonas-schulze / be_careful_with_dynamically_defining_methods.rb
Created March 15, 2018 11:24
Ruby Performance Tricks -- 6 Years Later -- Trick 7
require 'benchmark'
class Metric
N = 1_000_000
def self.class_eval_with_string
N.times do |i|
class_eval(<<-eorb, __FILE__, __LINE__ + 1)
def smeth_#{i}
#{i}
@jonas-schulze
jonas-schulze / use_bang_methods.rb
Last active March 15, 2018 12:04
Ruby Performance Tricks -- 6 Years Later -- Trick 4
require 'benchmark'
def merge!(array)
array.inject({}) { |h, e| h.merge!(e => e) }
end
def merge(array)
array.inject({}) { |h, e| h.merge(e => e) }
end