Why are try blocks expensive?

前端 未结 11 2452
醉酒成梦
醉酒成梦 2020-12-02 13:13

I\'ve heard the advice that you should avoid try catch blocks if possible since they\'re expensive.

My question is specifically about the .NET platform: Why are try

11条回答
  •  心在旅途
    2020-12-02 13:30

    IMO this whole discussion is like saying "wow lops are expensive because I need to increment a counter... i'm not going to use them any more", or "wow creating an object takes time, i'm not going to create a ton of objects any more."

    Bottom line is your adding code, presumably for a reason. If the lines of code didn't then incur some overhead, even if its 1 CPU cycle, then why would it exist? Nothing is free.

    The wise thing to do, as with any line of code you add to your application, is to only put it there if you need it to do something. If catching an exception is something you need to do, then do it... just like if you need a string to store something, create a new string. By the same means, if you declare a variable that isn't ever used, you are wasting memory and CPU cycles to create it and it should be removed. same with a try/catch.

    In other words, if there's code there to do something, then assume that doing something is going to consume CPU and/or memory in some way.

提交回复
热议问题