Hash.default-based euler code is slower under JRuby than Ruby 1.9.1
-------------------------------------------------------------------

                 Key: JRUBY-3315
                 URL: http://jira.codehaus.org/browse/JRUBY-3315
             Project: JRuby
          Issue Type: Bug
          Components: Performance
            Reporter: Charles Oliver Nutter


This code runs slower under JRuby than under 1.9.1. Have not done much 
investigation so far.

{noformat}
#!/usr/bin/env jruby
#!/usr/bin/env ruby1.9

# This is quite elegant (IMO), but also VERY slow under MRI 1.8. Run
# under jruby or ruby1.9!

# The problem:
# 
# If a number is even, divide it by two; if it is odd, multiply by
# three and add one. So if we start with the number 13, the sequence
# goes 13 -> 40 -> 20 -> 10 -> 5 -> 16 -> 8 -> 4 -> 2 -> 1. This
# "chain" is 10 links long. (Sequence ends when you reach 1).
# 
# Project Euler #14 wants to know: what number, less than 1_000_000,
# generates the longest chain? (Later numbers in the chain can go over
# 1M, but the first number must be <= 1M.)

# Here's my solution; I am trying for elegant/readable/tight/clean
# code.

h = Hash.new {|h,k| h[k] = (1 + ((k % 2 == 0) ? h[k/2] : h[3*k+1])) }
h[1] = 1
puts m = (1..1000000).map {|i| h[i]}.max

# This runs in about 100s on Ruby 1.8.
# 
# - Initting a hash with a proc is elegant and clean, but slow. It
#   went from 100s -> 16s after I wrote code to cache the results by
#   hand.
# 
# - Looping with downto instead of using map/max prevents duplication
#   of the array. This results in another 16s -> 4s speed impromevent.
# 
# - Interestingly, in the hash init proc, I noticed that h might be
#   aliasing to the external h variable, so I changed the inner
#   variables to |hash,key|. It certainly did have an effect: this
#   *added* 20sec to the execution time. Curious.
{noformat}

-- 
This message is automatically generated by JIRA.
-
If you think it was sent incorrectly contact one of the administrators: 
http://jira.codehaus.org/secure/Administrators.jspa
-
For more information on JIRA, see: http://www.atlassian.com/software/jira

        

---------------------------------------------------------------------
To unsubscribe from this list, please visit:

    http://xircles.codehaus.org/manage_email


Reply via email to