我正在编写高频交易软件。我确实关心每一微秒。现在它是用 C# 编写的,但我很快就会迁移到 C++。
让我们考虑这样的代码
// Original
class Foo {
....
// method is called from one thread only so no need to be thread-safe
public void FrequentlyCalledMethod() {
var actions = new List<Action>();
for (int i = 0; i < 10; i++) {
actions.Add(new Action(....));
}
// use actions, synchronous
executor.Execute(actions);
// now actions can be deleted
}
我想超低延迟的软件不应该过多地使用“new”关键字,所以我搬到actions
了一个领域:
// Version 1
class Foo {
....
private List<Action> actions = new List<Action>();
// method is called from one thread only so no need to be thread-safe
public void FrequentlyCalledMethod() {
actions.Clear()
for (int i = 0; i < 10; i++) {
actions.Add(new Action { type = ActionType.AddOrder; price = 100 + i; });
}
// use actions, synchronous
executor.Execute(actions);
// now actions can be deleted
}
也许我应该尽量避免使用“new”关键字?我可以使用一些预分配对象的“池”:
// Version 2
class Foo {
....
private List<Action> actions = new List<Action>();
private Action[] actionPool = new Action[10];
// method is called from one thread only so no need to be thread-safe
public void FrequentlyCalledMethod() {
actions.Clear()
for (int i = 0; i < 10; i++) {
var action = actionsPool[i];
action.type = ActionType.AddOrder;
action.price = 100 + i;
actions.Add(action);
}
// use actions, synchronous
executor.Execute(actions);
// now actions can be deleted
}
- 我应该走多远?
- 避免有多重要
new
? - 使用我只需要配置的预分配对象时,我会赢得什么吗?(在上面的示例中设置类型和价格)
请注意,这是超低延迟,所以让我们假设性能优于可读性、可维护性等。