ruby - Why is this imperative style faster than this functional style? -


say have array want find equilibrium index, why imperative style faster functional style, , logic behind algorithm (imperative's)?

functional style:

def eq_indices(list)   list.each_index.select |i|     list[0...i].inject(0, :+) == list[i+1..-1].inject(0, :+)   end end 

imperative style:

def eq_indices(list)   left, right = 0, list.inject(0, :+)   equilibrium_indices = []    list.each_with_index |val, i|     right -= val     equilibrium_indices << if right == left     left += val   end    equilibrium_indices end 

because in functional style, sum of left , right sides calculated scratch each potential equilibrium, whereas in imperative style, sum calculated once, , single subtraction , addition performed each potential equilibrium.


Comments

Popular posts from this blog

java - UnknownEntityTypeException: Unable to locate persister (Hibernate 5.0) -

python - ValueError: empty vocabulary; perhaps the documents only contain stop words -

ubuntu - collect2: fatal error: ld terminated with signal 9 [Killed] -