Story Details

  • 0+0 > 0: C++ thread-local storage performance

    Posted: 2025-02-17 11:18:29

    Thread-local storage (TLS) in C++ can introduce significant performance overhead, even when unused. The author benchmarks various TLS access methods, demonstrating that even seemingly simple zero-initialized thread-local variables incur a cost, especially on Windows. This overhead stems from the runtime needing to manage per-thread data structures, including lazy initialization and destruction. While the performance impact might be negligible in many applications, it can become noticeable in highly concurrent, performance-sensitive scenarios, particularly with a large number of threads. The author explores techniques to mitigate this overhead, such as using compile-time initialization or avoiding TLS altogether if practical. By understanding the costs associated with TLS, developers can make informed decisions about its usage and optimize their multithreaded C++ applications for better performance.

    Summary of Comments ( 10 )
    https://news.ycombinator.com/item?id=43077675

    The Hacker News comments discuss the surprising performance cost of thread-local storage (TLS) in C++, particularly its impact on seemingly unrelated code. Several commenters highlight the overhead introduced by the TLS lookups, even when the TLS variables aren't directly used in a particular code path. The most compelling comments delve into the underlying reasons for this, citing issues like increased register pressure due to the extra variables needing to be tracked, and the difficulty compilers have in optimizing around TLS access. Some point out that the benchmark's reliance on rdtsc for timing might be flawed, while others offer alternative benchmarking strategies. The performance impact is acknowledged to be architecture-dependent, with some suggesting mitigations like using compile-time initialization or alternative threading models if TLS performance is critical. A few commenters also mention similar performance issues they've encountered with TLS in other languages, suggesting it's not a C++-specific problem.