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

后端 未结 8 1367
青春惊慌失措
青春惊慌失措 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:46

    As Frank said, "as for performance: measure before you optimize." Repeating it to emphasize.

    Also, if you're creating a bunch of objects in a method, you don't need to use a try..finally block for each of them. That can lead to an ugly indentation mess. create, try, create, try, create, try, do something, finally, free, finally, free, finally, free. Ugh! Instead, you can set the object references to nil at the top of the method, then create them all, do one try block, and free them all in the finally section.

    That'll save some overhead and performance, (though you'll probably never notice the difference,) but more importantly it'll make your code cleaner and easier to read while maintaining the same level of safety.

提交回复
热议问题