如何加速我的面向对象迭代器类?
在问题抽象类的快速灵活迭代器的帮助下,我创建了抽象类 GridData 的抽象 GridIterator。现在我可以使用 GridIterator 的任何具体子类来迭代 GridData 的任何具体子类。
然而,在测试过程中,我发现虚拟运算符++和虚拟运算符*运算符成为我的算法的真正瓶颈。我想知道是否可以做些什么来加快速度。由于抽象,内联可能对我不起作用?
我也想提供一个 const Iterator。我不确定如何使其与当前的类设计一起工作。参考我原来的问题(抽象类的快速灵活的迭代器) ,我可以使用 const T 而不是 T 创建一个 ConstGridIterator 作为 STL 前向迭代器的子类吗?或者我是否必须实现每个迭代器类(GridIterator 和 baseImpl)的 const 版本?
With help in the question Fast and flexible iterator for abstract class I created an abstract GridIterator for an abstract class GridData. Now I am able to use any concrete subclass of GridIterator to iterate through any concrete subclass of GridData.
However, during testing I found out that the virtual operator++ and virtual operator* operators become real bottlenecks of my algorithms. I am wondering if there is anything I can do to speed it up. Because of the abstraction, inlining probably won't work for me?
I'd like to provide a const Iterator as well. I am not sure how to make this work with the current class design. Referring to my original question ( Fast and flexible iterator for abstract class ), can I just create a ConstGridIterator as subclass from a STL forward iterator with const T instead of T? Or do I have to implement a const version of every single iterator class (the GridIterator and baseImpl)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
按照 STL 进行操作,不要在迭代器或容器中使用虚拟方法。当要求优化时,大多数编译器都能够优化大多数 STL 迭代器,使其完全被绕过,甚至不存在于目标文件中。例如,
*(vector.begin()+5)
可以优化为vector.__underlying_array[5]
即使vector::iterator
是一个具有构造函数、析构函数和复杂运算符重定义的复杂类。在
operator++
、begin()
、end()
或operator !=() 的调用堆栈中的任意位置进行虚拟方法调用
阻止编译器正确优化它,因为该方法可以被任何东西重新定义。虚拟方法不仅具有较小的运行时开销,而且还使代码变得更加模块化,从而使代码变得不可优化。如果您想要性能,请考虑使用模板而不是继承,或者调整您的编译器,说没有人继承此类。这可能与您当前的设计相冲突,但您需要在这三个优先级中选择两个优先级:性能、模块化和成本。
Do as the STL and don't use virtual methods in an iterator or containers. Most compilers, when asked to optimize, are able to optimize out most STL iterators to the point they are completely bypassed and they don't even exist in the object file. For example a
*(vector<T>.begin()+5)
could be optimized tovector<T>.__underlying_array[5]
even ifvector<T>::iterator
is a complex class with constructors, destructors and complex operator redefinitions.Having a virtual method call anywhere in the call stack of
operator++
,begin()
,end()
oroperator !=()
prevent the compiler to optimize this correctly because the method could be redefined by anything. virtual methods don't only have a small runtime overhead, they make the code unoptimizable by making it more modular.If you want performance, consider using templates instead of inheritance, or tweak your compiler, saying that nobody inherit this class. This may conflict with your current design, but you need to choose two priorities among those three : performance, modularity and cost.