performance - Which of these Array Initializations is better in Ruby? -


Which of these two lines is better to start in Ruby?

Method 1:

  DAYS_IN_A_WEEK = (0..6) .to_a HOURS_IN_A_DAY = (0..23) .to_a @data = Array.new (DAYS_IN_A_WEEK.size) .map! {Array .new (HOURS_IN_A_DAY.size)} DAYS_IN_A_WEEK.each Do it. Day | HOURS_IN_A_DAY.each do | Hours. @ Data [days] [hours] = 'some end'  

method 2:

  DAYS_IN_A_WEEK = (0. .6) .to_a HOURS_IN_A_DAY = (0..23) .to_a @data = {} DAYS_IN_A_WEEK.each Do it. Day | HOURS_IN_A_DAY.each do | Hours. @data [day] || = {} @ Data [day] [hour] = 'end of end'  

The difference between the first method and the second method is that the second does not allocate memory initially I think the second one is very inferior, when it comes to performances due to several copies of the effect on it.

However, it is not straight forward in Ruby to know what is happening. So, if someone could explain to me which one is better, then it would be great!

Thank you

Before I answer the question you asked, I I am going to answer the question you should ask, but no:

Question: Is focusing on making my code readable before, Or should I pay attention to the performance first?

A: first and correct your code read, then, and only if any functionality If the problem is, start worrying about performance by measuring where the display problem is first and only then is making changes to its code.

Now to answer the question you asked, but this should not be:

method1.rb:

  DAYS_IN_A_WEEK = ( 0..6) .to_a HOURS_IN_A_DAY = (0..23) .to_a does 10000.times @data = Array.new (DAYS_IN_A_WEEK.size) .map! {Array.new (HOURS_IN_A_DAY.size)} DAYS_IN_ A_WEEK.each Do it. Day | HOURS_IN_A_DAY.each do | Hours. @ Data [days] [hours] = 'some end-end  

method2.rb:

  DAYS_IN_A_WEEK = (0..6) .to_a HOURS_IN_A_DAY = (0..23) .to_a 10000.times do @data = {} do DAYS_IN_A_WEEK.each. Day | HOURS_IN_A_DAY.each do | Hours. Results of brain-dead benchmarks:  
 @data [day] || = {} @data [day] [hours] = 'somewhat' end end end  

$ time dark red color method1.rb real 0m1.189s user sys 0m0.000s $ Time dark red color method2.rb real 0m1.879s user sys 0m0.020s 0m1.780s 0m1.140s

I think user time use (critical factor) method 1 RB is very fast You should definitely not believe this benchmark, and you should show your actual code usage. However, you should only do this after that , it has been determined how your code is actually displayed in the code (signal: 99.44% of computer programmer is 100% wrong When they guess without measuring their obstacles!)


Comments

Popular posts from this blog

windows - Heroku throws SQLITE3 Read only exception -

lex - Building a lexical Analyzer in Java -

python - rename keys in a dictionary -