c++ - 我应该在 C++ (SFML)中缓存这个对象吗
问题描述
(我对 c++ 完全陌生,但我在 c# 和 java 方面有经验)
嗨,我正在用 C++(SFML)创建一个国际象棋游戏,并且我有一个具有 draw 方法的 Piece 类。现在我正在这样做:
void Piece::draw(sf::RenderWindow& p_window, bool p_selected) {
if (p_selected) {
sf::RectangleShape shape;
shape.setFillColor(sf::Color(190,235,127));
shape.setOutlineColor(sf::Color(221,237,142));
shape.setOutlineThickness(3);
shape.setSize(sf::Vector2f(80,80));
shape.setPosition(sprite.getPosition());
p_window.draw(shape);
}
p_window.draw(sprite);
}
如果选择了这块,我创建 RectangleShape(让玩家知道选择了哪块),设置它的属性,然后绘制它。
这是这样做的好方法吗?或者我应该使用设置的属性缓存 RectangleShape 并将其位置更新为选定的块位置?
如果我错过了重要的事情,请告诉我,谢谢您的回答。
解决方案
实际上,缓存与不缓存 sf::RectangleShape 相比,对性能的影响很小,尤其是对于像棋类游戏这样相对简单的程序。不过,一般来说,缓存每帧重复使用的变量而不是一遍又一遍地创建它们是一个好主意。我决定使用您提供的代码编写一个小型测试用例,以测量超过 10,000 次绘图调用的性能差异。结果是大约 23% 的性能提升(1518 毫秒对 1030 毫秒)。这是我使用的代码,以便您可以自己测试:
#include <SFML/Graphics.hpp>
#include <iostream>
class Test {
public:
static sf::RectangleShape rect;
Test() {
rect.setFillColor(sf::Color(190, 235, 127));
rect.setOutlineColor(sf::Color(221, 237, 142));
rect.setOutlineThickness(3);
rect.setSize(sf::Vector2f(80, 80));
rect.setPosition(0, 0);
}
void drawNoCache(sf::RenderWindow& p_window) {
sf::RectangleShape shape;
shape.setFillColor(sf::Color(190, 235, 127));
shape.setOutlineColor(sf::Color(221, 237, 142));
shape.setOutlineThickness(3);
shape.setSize(sf::Vector2f(80, 80));
shape.setPosition(0, 0);
p_window.draw(shape);
}
void drawWithCache(sf::RenderWindow& p_window) {
p_window.draw(rect);
}
};
sf::RectangleShape Test::rect;
int main() {
sf::RenderWindow window(sf::VideoMode(80, 80), "SFML");
Test t;
sf::Clock clock;
clock.restart();
for (int i = 0; i < 10000; i++) {
window.clear(sf::Color(0, 0, 0));
t.drawNoCache(window);
window.display();
}
std::cout << clock.restart().asMilliseconds() << std::endl;
for (int i = 0; i < 10000; i++) {
window.clear(sf::Color(0, 0, 0));
t.drawWithCache(window);
window.display();
}
std::cout << clock.restart().asMilliseconds() << std::endl;
}
推荐阅读
- maven - 将 Maven 项目导入 IntelliJ 2019.3 后,捆绑的类不在类路径上
- ruby-on-rails - 如何将元数据添加到 csv 文件?
- java - java中的组合和聚合有什么区别?
- php - 如何在php中获得超过24小时的时间间隔
- vba - 是否有“Application.Wait”方法
- linux - 为什么内核代码中有多个位置的同一个文件?
- salesforce - 如何使用 jitterbit 从 Salesforce 查询大数据
- c# - C# Entity Framework,删除子项然后删除父项,DELETE 语句与 REFERENCE 约束冲突
- r - 如何在同一数据中拟合两个线性回归?
- javascript - 如何使用 React Redux 将道具传递给子组件?