0

Which cast is faster? static_cast of object pointers or static_cast of shared_ptr?

Example in qt:

class Base;
class Derived:Base;

auto newBase = QSharedPointer<Base>::create();
auto Derived1 = static_cast<Derived*>(newBase.data());
auto Derived2 = qSharedPointerCast<Derived>(newBase);

Which operation is faster and why? (i may have some syntax errors, but i hope i'm not).

Sisir
  • 4,584
  • 4
  • 26
  • 37
Ivan
  • 43
  • 4
  • Both casts perform in compile-time not in run-time. Do you really interested in some usec in compilation? Anyway `static_cast` should be faster. `qSharedPointerCast` perform additional checks and then call `static cast`. – Konstantin T. May 30 '17 at 07:46
  • @KonstantinT. Does the counter in QSharedPointer increase when i perform cast? Thank you. – Ivan May 30 '17 at 08:00
  • If you perform static cast counter will **not** increase. It mean that counter will same as before you perform cast. If you perform qSharedPointerCast you will have two sharedpointer and counter will equal two. – Konstantin T. May 30 '17 at 09:25
  • @KonstantinT. "_Both casts perform in compile-time not in run-time_" what do you mean? – curiousguy May 30 '17 at 18:38

2 Answers2

2

The qSharedPointerCast copies the pointer, thus incrementing the data block's reference count, and costs you a locked cacheline update. The static_cast<Derived*>(newBase.data()) uses the pointer already in existence and doesn't increase anything - it's only a type safety compile-time construct, it has no overhead.

Kuba hasn't forgotten Monica
  • 95,931
  • 16
  • 151
  • 313
0

Since newBase holds instance of Base and you cast to Derived, your example is clearly undefined behavior (a bug in code).

auto Derived1 = static_cast<Derived*>(newBase.data()); must be a bit faster since it doesn't create new strong reference so reference counter is not increased. qSharedPointerCast<Derived>(newBase) has to do it.

Anyway speed difference is so small that it is irrelevant. You are warring about micro-optimization. I doubt you will notice significant difference if you do some measurement.

Please focus your efforts on understanding inheritance (dependency inversion) and how pointers are handling that and ignore for now this tiny optimizations.

Marek R
  • 32,568
  • 6
  • 55
  • 140