gpt4 book ai didi

C++ 类与实用函数

转载 作者:太空狗 更新时间:2023-10-29 21:46:43 25 4
gpt4 key购买 nike

所以我可能想要在一条线上运行的各种函数:

inline float yIntercept(const vec2& ptA, const vec2& ptB, float x);
inline float xIntercept(const vec2& ptA, const vec2& ptB, float y);
inline bool lineIntersection(const vec2& ptA0, const vec2& ptB0, const vec2& ptA1, const vec2& ptB1);

函数对代表该线的每条线取 2 个点。

或者我可以编写一个包含这 2 个点和各种有用的线相关方法的线类。

struct Line {
... stuff

inline float xIntercept(float y);
inline float yIntercept(float x);

inline bool lineIntersection(const Line& other);

vec2 m_point[2];
};

我在考虑的一件事是每次我需要调用这些函数之一时创建这个线类的实例的性能,只需给定 2 分。

我可能正在对表示多边形的点列表进行操作,但实际上并没有实例化任何线对象。

我可以随时打电话

yIntercept(somePointA, somePointB, 3.0f);

或者

Line(somePointA, somePointB).yIntercept(3.0f);  //I think this would compile

我喜欢为这类事物提供类而不是 C 风格函数的想法,但我想知道像这样创建类的实例而不是将点直接传递给函数是否会降低性能。也许编译器做了一些优化?

最佳答案

One thing I was thinking about is performance of creating an instance of this line class every time I need to call one of these functions just given 2 points.

如果这确实是您应用程序中的问题,那么您可能“做错了”。我的意思是,如果做得好,创建这个对象的代码应该非常轻量级。即便如此,您是否真的需要创建很多这样的对象 - 做构成线条的“事物”不会随着时间的推移而存在,因此 struct Line 可以以某种方式成为覆盖对象的一部分。

例如,在多边形中,您可以从点列表中创建线对象,并将它们保留在周围。

我也会先编写一个通用的、运行良好的代码库,然后在一切正常时进行优化。如果你必须重写一些东西,那就这样吧。希望您已经使您的接口(interface)足够通用,以至于您不必重写太多其他代码。

无论何时进行性能优化,都要确保进行衡量、再衡量,并记下您为改变它所做的工作。我有时在电子表格中有几百行“尝试修改 X”、“在函数 A 中使用了巧妙的技巧”以及结果——有时结果是“丢失 5%”(或“丢失 500%”),但在至少你知道结果是什么。使用“我认为编译器会这样做”需要对任何给定编译器有很多经验。

关于C++ 类与实用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14539967/

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