I'm running code which works fast locally, but when it's on Heroku it's slow. Heroku says this is because there is less memory and CPU power on my hosting than locally. I'm trying to rewrite my code so it's more efficient, but I'm not sure how.
This is what they said:
...[my] method (especially, a.each part) is taking time. I think a itself is pretty long, and you're transpose it with subs.keys, and do some process for each of them. Even though
s.gsub!(*pair)is not "long running" code, if you run this million times (actually runs 1,161,216 times for the word "startup"), it'll be "slow" request.
Here is my code:
def substitute(word)
subs = Hash.new
Section.all.to_a.each do |s|
alternates_array = Array.new
s.substitutions.each do |alt|
alternates_array << alt.alternate
end
alternates_array << s.part
new_hash = Hash.new
subs[s.part] = alternates_array
end
a = subs.values
a = a.first.product(*a.drop(1))
alternates = Array.new
a.each do |a|
new_string = [subs.keys, a].transpose.each_with_object(word.dup){|pair, s| s.gsub!(*pair)}
end
return alternates
end
Section Model
class Section
include Mongoid::Document
field :part, type: String
embeds_many :substitutions
accepts_nested_attributes_for :substitutions
end
Substitution Model
class Substitution
include Mongoid::Document
field :alternate, type: String
embedded_in :section
end