How I can write file from a tester to the MQL5/Files folder? - page 2

 
Since you mentioned  OnTesterDeInit() your question is about optimization. Then you can use FrameAdd from OnTester (which is running in a tester agent), and receive this data by FrameFirst/FrameNext in OnTesterPass (which is running in the context of the terminal, and MQL5/Files are accessible), so you can save the data into a file there.