Which part of throwing an Exception is expensive?

后端 未结 6 2034
盖世英雄少女心
盖世英雄少女心 2020-11-30 16:52

In Java, using throw/catch as a part of logic when there\'s not actually an error is generally a bad idea (in part) because throwing and catching an exception is expensive,

6条回答
  •  孤城傲影
    2020-11-30 17:09

    This part of the question...

    Another way of asking this is, if I made one instance of Exception and threw and caught it over and over, would that be significantly faster than creating a new Exception every time I throw?

    Seems to be asking if creating an exception and caching it somewhere improves performance. Yes it does. It's the same as turning off the stack being written on object creation because it's already been done.

    These are timings I got, please read caveat after this...

    |Depth| WriteStack(ms)| !WriteStack(ms)| Diff(%)|
    |   16|            193|             251| 77 (%)| 
    |   15|            390|             406| 96 (%)| 
    |   14|            394|             401| 98 (%)| 
    |   13|            381|             385| 99 (%)| 
    |   12|            387|             370| 105 (%)| 
    |   11|            368|             376| 98 (%)| 
    |   10|            188|             192| 98 (%)| 
    |    9|            193|             195| 99 (%)| 
    |    8|            200|             188| 106 (%)| 
    |    7|            187|             184| 102 (%)| 
    |    6|            196|             200| 98 (%)| 
    |    5|            197|             193| 102 (%)| 
    |    4|            198|             190| 104 (%)| 
    |    3|            193|             183| 105 (%)| 
    

    Of course the problem with this is your stack trace now points to where you instantiated the object not where it was thrown from.

提交回复
热议问题