冷凝代码行

时间:2014-03-13 01:13:30

标签: java optimization indexing

如果我有下面的代码行,那么有什么方法可以将它压缩成1或2行并使用循环或类似的东西?有超过100个索引,因此要写出大量文本。

unrlzdPnl = 
(((Positions[0].GetProfitLoss(Closes[0][0], PerformanceUnit.Points))*200)
+ ((Positions[1].GetProfitLoss(Closes[1][0], PerformanceUnit.Points))*200)
+ ((Positions[2].GetProfitLoss(Closes[2][0], PerformanceUnit.Points))*200)
+ ((Positions[3].GetProfitLoss(Closes[3][0], PerformanceUnit.Points))*200)
+ ((Positions[4].GetProfitLoss(Closes[4][0], PerformanceUnit.Points))*200)
+ ((Positions[5].GetProfitLoss(Closes[5][0], PerformanceUnit.Points))*200)
+ ((Positions[6].GetProfitLoss(Closes[6][0], PerformanceUnit.Points))*200)
);

1 个答案:

答案 0 :(得分:0)

也许我不明白,但我会说:

int unrlzPnl = 0;
for (int i = 0; i < nb_indices; i++) {
    unrlzdPnl += Positions[i].GetProfitLoss(Closes[i][0],
                                            PerformanceUnit.Points);
}
unrlzPnl *= 200;

编辑#1:

不要忘记在循环之前初始化unrlzPnl。如果你想看看每次迭代会发生什么(假设你正在使用Java):

int unrlzPnl = 0;
for (int i = 0; i < nb_indices; i++) {
    System.out.println("Iteration " + i + ":");
    System.out.println("unrlzdPnl (old): " + unrlzdPnl);
    unrlzdPnl += Positions[i].GetProfitLoss(Closes[i][0],
                                            PerformanceUnit.Points);
    System.out.println("unrlzdPnl (new): " + unrlzdPnl + "\n");
}
return unrlzPnl * 200;
System.out.println("unrlzdPnl (final value): " + unrlzdPnl);

编辑#2:

好的,如果你真的希望它尽可能紧凑,并且每次调用函数时都要避免初始化:

int MyFunction(int nb_indices) {
    if (1 > nb_indices)
        return 0;

    unrlzdPnl = Positions[0].GetProfitLoss(Closes[0][0],
                                           PerformanceUnit.Points);

    for (int i = 1; i < nb_indices; i++)
        unrlzdPnl += Positions[i].GetProfitLoss(Closes[i][0],
                                                PerformanceUnit.Points);

    return unrlzPnl * 200;
}