gpt4 book ai didi

C++ 静态内部函数

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:17:39 25 4
gpt4 key购买 nike

你好,我有一个函数返回一个 std::pair 并且经常被调用。

std::pair<sf::Vector2i, sf::Vector2i> 
Map::map_coord_to_chunk_coord(int x, int y) {
// Get the chunk position
int chunk_x = x / CHUNK_SIZE;
int chunk_y = y / CHUNK_SIZE;

// Get the position inside the chunk
x = x - chunk_x * CHUNK_SIZE;
y = y - chunk_y * CHUNK_SIZE;

// Return the chunk position and the position inside it
return std::pair<sf::Vector2i, sf::Vector2i>(sf::Vector2i(chunk_x,
chunk_y), sf::Vector2i(x, y));
}

将对声明为静态是否更好,这样它就不会每次都创建。

std::pair<sf::Vector2i, sf::Vector2i> 
Map::map_coord_to_chunk_coord(int x, int y) {
static std::pair<sf::Vector2i, sf::Vector2i> coords;

// Get the chunk position
coords.first.x = x / CHUNK_SIZE;
coords.first.y = y / CHUNK_SIZE;

// Get the position inside the chunk
coords.second.x = x - coords.first.x * CHUNK_SIZE;
coords.second.y = y - coords.first.y * CHUNK_SIZE;

// Return the chunk position and the position inside it
return coords;
}

我运行 callgrind,看起来这个函数快了 3 倍,但这是一个好的做法吗?

最佳答案

一般来说,当唯一的目标是节省 CPU 周期时,应该避免使用 static

使 coords 静态呈现您的 map_coord_to_chunk_coord 函数 non-reentrant ,这意味着它在没有适当同步的情况下不再可用于并发环境。这是为节省简单对象的构造成本而付出的非常高的代价。

例如,您应该能够使用 make_pair 优化 std::pair 的构造:

inline std::pair<sf::Vector2i, sf::Vector2i> 
Map::map_coord_to_chunk_coord(int x, int y) {
int first_x = x / CHUNK_SIZE;
int first_y = y / CHUNK_SIZE;
return std::make_pair(
sf::Vector2i(first_x, first_y)
, sf::Vector2i(x - first_x * CHUNK_SIZE, y - first_y * CHUNK_SIZE)
);
}

在某些情况下,编译器 can even optimize out the copying , 进一步提高性能。

关于C++ 静态内部函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43978640/

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