【发布时间】:2017-05-15 21:47:45
【问题描述】:
您好,我有一个返回 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 倍,但这是一个好习惯吗?
【问题讨论】:
-
在什么方面更好? “良好做法”是基于意见的。
-
这个坐标只能在这个函数中使用?我的意思是你声明了对象坐标并且只有在 map_coord_to_chunk_coord 里面才能使用它?
-
你是如何测量速度增加的?我认为
return {{(chunk_x, chunk_y}, {x, y}};可以正常工作 -
是的,只有这个函数使用它,通过良好的实践,我的意思是这会产生一些问题吗?
-
@Snps 这绝对是关于整数除法,否则计算将毫无意义。
标签: c++