Void Pointers and std::any

Performance Impact of std::any

Does using std::any have a significant performance impact compared to using concrete types directly?

Illustration representing computer hardware

Yes, using std::any does have a performance cost compared to using concrete types directly.

When you use a concrete type, the compiler knows the exact size and layout of the object. This allows it to generate efficient code for creating, copying, and accessing the object.

With std::any, the actual type is not known at compile-time. std::any has to store the value in dynamically allocated memory and manage that memory. Accessing the value requires a runtime type check (via std::any_cast) and a potential copy.

Here's an example:

std::any a = 42;

// Runtime type check, potential copy
int i = std::any_cast<int>(a);

Compared to:

int a = 42;
int i = a;// No runtime overhead

The performance hit of std::any is most significant when:

  • The type stored in the std::any is large (more data to copy)
  • The std::any is accessed frequently (more type checks and copies)

Therefore, it's best to avoid std::any in performance-critical code, unless the flexibility it provides is truly necessary. When you do use std::any, try to minimize the number of times the value is accessed or copied.

Remember, premature optimization is the root of all evil. Use concrete types by default, and only introduce std::any when the need for runtime polymorphism is clear and justified.

Answers to questions are automatically generated and may not have been reviewed.

A computer programmer
Part of the course:

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, unlimited access

This course includes:

  • 124 Lessons
  • 550+ Code Samples
  • 96% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved