gpt4 book ai didi

c# - 我应该尽量避免在超低延迟软件中使用 "new"关键字吗?

转载 作者:行者123 更新时间:2023-12-02 14:25:33 27 4
gpt4 key购买 nike

我正在编写高频交易软件。我确实关心每一微秒。现在它是用 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有多重要?
  • 使用我只需要配置的预分配对象时我会赢得任何东西吗? (在上面的示例中设置类型和价格)

请注意,这是超低延迟,因此我们假设性能优先于可读性可维护性等。

最佳答案

在 C++ 中,您不需要 new 来创建范围有限的对象。

void FrequentlyCalledMethod() 
{
std::vector<Action> actions;
actions.reserve( 10 );
for (int i = 0; i < 10; i++)
{
actions.push_back( Action(....) );
}
// use actions, synchronous
executor.Execute(actions);
// now actions can be deleted
}

如果 Action 是基类,并且您拥有的实际类型属于派生类,则您将需要一个指针或智能指针以及 new 。但是,如果 Action 是具体类型并且所有元素都是该类型,并且该类型是默认可构造、可复制和可分配的,则不需要。

但总的来说,不使用 new 不太可能带来性能优势。当局部函数作用域是对象的作用域时,在 C++ 中使用局部函数作用域是一种很好的做法。这是因为在 C++ 中,您必须更加关注资源管理,这是通过称为“RAII”的技术来完成的 - 这本质上意味着关注如何在调用时删除资源(通过对象的析构函数)。分配点。

高性能更有可能通过以下方式实现:

  • 正确使用算法
  • 适当的并行处理和同步技术
  • 有效的缓存和惰性求值。

关于c# - 我应该尽量避免在超低延迟软件中使用 "new"关键字吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14243128/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com