How to optimize this short factorial function in scala? (Creating 50000 BigInts)

前端 未结 4 1362
名媛妹妹
名媛妹妹 2021-02-13 06:41

I\'ve compaired the scala version

(BigInt(1) to BigInt(50000)).reduce(_ * _)

to the python version

reduce(lambda x,y: x*y, rang         


        
4条回答
  •  逝去的感伤
    2021-02-13 07:28

    Another trick here could be to try both reduceLeft and reduceRight to see what is fastest. On your example I get a much faster execution of reduceRight:

    scala> timed { (BigInt(1) to BigInt(50000)).reduceLeft(_ * _) }
    Took: 4605 ms
    
    scala> timed { (BigInt(1) to BigInt(50000)).reduceRight(_ * _) }
    Took: 2004 ms
    

    Same difference between foldLeft and foldRight. Guess it matters what side of the tree you start reducing from :)

提交回复
热议问题