我在Haskell和Scala中有一段非常簡單的代碼。此代碼旨在以非常嚴格的循環運行,因此性能很重要。問題是Haskell比Scala慢10倍左右。這裏是Haskell代碼。Haskell矢量性能與Scala相比
{-# LANGUAGE BangPatterns #-}
import qualified Data.Vector.Unboxed as VU
newtype AffineTransform = AffineTransform {get :: (VU.Vector Double)} deriving (Show)
{-# INLINE runAffineTransform #-}
runAffineTransform :: AffineTransform -> (Double, Double) -> (Double, Double)
runAffineTransform affTr (!x, !y) = (get affTr `VU.unsafeIndex` 0 * x + get affTr `VU.unsafeIndex` 1 * y + get affTr `VU.unsafeIndex` 2,
get affTr `VU.unsafeIndex` 3 * x + get affTr `VU.unsafeIndex` 4 * y + get affTr `VU.unsafeIndex` 5)
testAffineTransformSpeed :: AffineTransform -> Int -> (Double, Double)
testAffineTransformSpeed affTr count = go count (0.5, 0.5)
where go :: Int -> (Double, Double) -> (Double, Double)
go 0 res = res
go !n !res = go (n-1) (runAffineTransform affTr res)
還可以做些什麼來改進此代碼?
你是如何編譯它以及使用哪個編譯器的? –
它是用ghc 7.6.3編譯的。選項是「-O2-Wall -funbox-strict-fields -threaded -rtsopts」。我期望-funbox-strict-fields就足夠了,但事實並非如此。那麼,我是一個完整的新手,所以我的期望可能會有所改變。 – Aurimas
爲什麼你需要'Vector'來表示仿射變換?爲它製作ADT並處理座標數組似乎更合理。 – leventov