問題描述
我讀到使用 C++ 異常進行異常處理有一些開銷,而不是檢查返回值.我只是在談論沒有拋出異常時產生的開銷.我還假設您需要實現實際檢查返回值并執行適當操作的代碼,無論與 catch 塊所做的操作等效.而且,將拋出異常對象的代碼與其中包含 45 個狀態變量的代碼進行比較,并為每個錯誤返回一個負整數的代碼也是不公平的.
I have read that there is some overhead to using C++ exceptions for exception handling as opposed to, say, checking return values. I'm only talking about overhead that is incurred when no exception is thrown. I'm also assuming that you would need to implement the code that actually checks the return value and does the appropriate thing, whatever would be the equivalent to what the catch block would have done. And, it's also not fair to compare code that throws exception objects with 45 state variables inside to code that returns a negative integer for every error.
我不是試圖僅僅基于哪個可能執行得更快來構建支持或反對 C++ 異常的案例.我聽說最近有人提出這樣的案例,一旦您考慮到檢查返回值和處理錯誤所需的所有額外簿記代碼,使用異常的代碼應該與基于返回代碼的代碼一樣快地運行.我錯過了什么?
I'm not trying to build a case for or against C++ exceptions solely based on which one might execute faster. I heard someone make the case recently that code using exceptions ought to run just as fast as code based on return codes, once you take into account all the extra bookkeeping code that would be needed to check the return values and handle the errors. What am I missing?
推薦答案
某些 平臺和某些 編譯器上的異常處理會產生相關成本.
There is a cost associated with exception handling on some platforms and with some compilers.
也就是說,Visual Studio 在構建 32 位目標時,將在每個具有非平凡析構函數的局部變量的函數中注冊一個處理程序.基本上,它設置了一個 try/finally
處理程序.
Namely, Visual Studio, when building a 32-bit target, will register a handler in every function that has local variables with non-trivial destructor. Basically, it sets up a try/finally
handler.
gcc
和面向 64 位的 Visual Studio 采用的另一種技術僅在拋出異常時產生開銷(該技術涉及遍歷調用堆棧和表抬頭).在很少拋出異常的情況下,這實際上可以產生更高效的代碼,因為不必處理錯誤代碼.
The other technique, employed by gcc
and Visual Studio targeting 64-bits, only incurs overhead when an exception is thrown (the technique involves traversing the call stack and table lookup). In cases where exceptions are rarely thrown, this can actually lead to a more efficient code, as error codes don't have to be processed.
這篇關于當沒有異常時,C++ 異常會以何種方式減慢代碼速度?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!