Exception Cost
Exception Cost
Exception Cost in C++: try-catch vs malloc
Prerequisites
1. Why Exception Matters
C++ exceptions (try-catch) provide safe error handling, but they come with performance considerations.
Especially in performance-critical code, exception usage must be carefully evaluated.
Exceptions are zero-cost when not thrown, but very expensive when thrown
✔ When NOT thrown
1
2
3
4
5
6
7
try
{
foo();
}
catch (...)
{
}
Almost no runtime cost (modern compilers)
❌ When thrown
1
throw std::bad_alloc();
Heavy operations:
- Stack unwinding
- Destructor calls
- RTTI lookup
- Control transfer
❌ Can be orders of magnitude slower
2. Instead of Exception, Another
2-1. new vs malloc
✔ new
1
int* p = new int;
- Calls constructor
- Throws
std::bad_allocon failure
✔ malloc
1
int* p = (int*)malloc(sizeof(int));
- No constructor
- Returns
nullptron failure - No exception
| Feature | new | malloc |
|---|---|---|
| Failure handling | Exception | nullptr |
| Constructor call | Yes | No |
| Overhead | Higher | Lower |
| Safety | Higher | Lower |
2-1. When to Use malloc
✔ Plain data (POD / primitive types)
✔ Performance-critical paths
✔ When exception handling is undesirable
1
2
3
4
5
int* p = (int*)malloc(sizeof(int));
if (!p)
{
// handle error manually
}
2-2. When to Use new
✔ Complex objects
✔ RAII / constructor required
✔ Safety more important than raw speed
2-3. Exception-Free Design
👉 In high-performance systems:
- Avoid exceptions in hot paths
- Use error codes or flags
- Use pre-allocation / object pools
✔ DO
- Use
mallocfor simple data in critical loops - Check
nullptrmanually - Avoid exception-heavy flows
❌ DON’T
- Rely on exceptions for normal control flow
- Use
mallocfor complex objects - Ignore memory initialization
2-4. Advanced Tip
✔ new (std::nothrow)
1
2
3
4
5
int* p = new (std::nothrow) int;
if (!p)
{
// handle error
}
- Avoids exception
- Returns
nullptrlikemalloc
This post is licensed under CC BY 4.0 by the author.