Skip to content

Instantly share code, notes, and snippets.

Avatar

Jonas Schulze jonas-schulze

  • Germany
View GitHub Profile
@jonas-schulze
jonas-schulze / be_careful_with_dynamically_defining_methods.rb
Created Mar 15, 2018
Ruby Performance Tricks -- 6 Years Later -- Trick 7
View be_careful_with_dynamically_defining_methods.rb
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 / avoid_parallel_assignment.rb
Created Mar 15, 2018
Ruby Performance Tricks -- 6 Years Later -- Trick 6
View avoid_parallel_assignment.rb
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 / use_instance_variables.rb
Created Mar 15, 2018
Ruby Performance Tricks -- 6 Years Later -- Trick 5
View use_instance_variables.rb
require 'benchmark'
class Metric
attr_accessor :var
def initialize(n)
@n = n
@var = 22
end
@jonas-schulze
jonas-schulze / use_bang_methods.rb
Last active Mar 15, 2018
Ruby Performance Tricks -- 6 Years Later -- Trick 4
View use_bang_methods.rb
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
@jonas-schulze
jonas-schulze / be_careful_with_calculations_within_iterators.rb
Last active Mar 15, 2018
Ruby Performance Tricks -- 6 Years Later -- Trick 3
View be_careful_with_calculations_within_iterators.rb
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 / prefer_shift_over_pluseq_for_string_concatenation.rb
Last active Mar 15, 2018
Ruby Performance Tricks -- 6 Years Later -- Trick 2
View prefer_shift_over_pluseq_for_string_concatenation.rb
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 / do_not_use_exceptions_for_control_flow.rb
Last active Mar 15, 2018
Ruby Performance Tricks -- 6 Years Later -- Trick 1
View do_not_use_exceptions_for_control_flow.rb
require 'benchmark'
class Obj
def with_condition
respond_to?(:mythical_method) ? self.mythical_method : nil
end
def with_rescue
self.mythical_method
rescue NoMethodError
You can’t perform that action at this time.