爲了引用一些與鍵的座標我想使用區分的聯合類型,因爲它們允許各種高效的模式匹配。爲區分的聯合類型實現快速的CustomEquality和CustomComparison
考慮follwoing一小段代碼片段:
[<CustomEquality; CustomComparison>]
type Coord =
| Spot of AssetKey
| Vol of AssetKey * DateTime option
| Rate of Currency
.....
member this.sortKey =
match this with
| Spot(key) -> (0 , key.toString)
| Vol(key) -> (1 , key.toString)
| Vol(key, Some(t)) -> (2 , key.toString + t.ToShortString())
| Rate(cur) -> (3 , cur.toString)
......
interface IComparable with
member this.CompareTo(obj) =
match obj with
| :? Coord as other -> compare this.sortKey other.sortKey
| _ -> invalidArg "obj" "not a Coord type"
override this.Equals(obj) =
match obj with
| :? Coord as other -> this.sortKey = other.sortKey
| _ -> false
override this.GetHashCode() = this.sortKey.GetHashCode()
我需要強制執行特定的排序順序。例如Spot < Vol總是。我用sortKey成員函數強制執行。
的AssetKey是再次非常類似區分聯合類型:
[<StructuralEqualityAttribute; StructuralComparisonAttribute>]
type AssetKey =
| Equity of string
| EquityIndex of string
.....
所以這一切都工作得很好,但它是緩慢的。據我所知,如果調用sortKey函數,整個鍵就會重新構建,特別是toString函數會再次被調用。
一個明顯的改進是添加一個緩存層,這比解決方案更像是一種破解。
進一步的優化是在字符串上使用散列鍵。但是在這裏我需要添加緩存,因爲我需要緩存散列鍵,我不想重新計算它。
的性能優化會更容易,如果我使用一個結構或類,但然後我鬆模式匹配等的靈活性例如
match c with
| Coord.Vol(ak, _) when ak = assetKey -> true
| _ -> false
將是什麼的另一種方法,這是很好執行?在我的一些定時中,sortKey函數中有30%以上的整體性能丟失。
感謝您的任何建議和改進。
嗨感謝您的幫助。我實現了第一個版本,速度大約快100倍。這是我的實現: – Daniel 2012-03-01 17:15:50