Should I put a try-finally block after every Object.Create?

后端 未结 8 1386
青春惊慌失措
青春惊慌失措 2021-02-04 17:11

I have a general question about best practice in OO Delphi. Currently, I put try-finally blocks anywhere I create an object to free that object after usage (to avoid memory leak

8条回答
  •  旧巷少年郎
    2021-02-04 17:52

    Even if it is much recommended to do that, I won't always do it.

    My rules of using or not using the try/finally:

    • The chance for that object to crash and burn.
    • Number of times the object is created. If I know that your object is created rarely (not more than 5-6 time in application life time) I can live with a 20KB memory leak - in case it 'dies' without being freed.
    • Amount of leaked memory in case the object crashes.
    • Code complexity. Try/except is making the code to look really ugly. If there is a 5 lines procedure, I always use try/except.
    • Application file span. If your application needs to run for days, then I definitively want to free ANY piece of memory else the leak will accumulate.

    The only place where is difficult to make a decision is when you need performance while creating the object thousands of times (in a loop for example). In this case, I don't use try/except if the object is performing simple tasks and there is a small chance to see it crashing.

提交回复
热议问题