Writing very large TTrees

I’m attempting to create a TTree object with multiple branches. During a Geant4 run several objects that descend from TObject are created, namely an event object and some hit objects. At the beginning of a run I have the following lines:

	f = new TFile("output.root", "RECREATE");
	tree = new TTree("tree", "Data");

Then at the end of each event within the run I have the following lines:

		f->cd();
		tree->Branch("Event", "TEvent", &event, 64000, 99);
		tree->Fill();
		f->Write();

At the end I obviously close the file. Everything works and my data is retrievable, however I noticed that my output file was growing exponentially with the number of events run instead of linearly. Calling Map() on the file revealed that the tree was being written multiple times at different stages. For example, if I run 10 events, there are 10 trees. The first has 1 branch, the second has 2 branches, etc. The simple solution is to wait to call Write() until the end of an entire run. However, this simulation is quite large and cannot afford to store the entire tree in memory to be written at the end and event objects are cleared after each event is finished. Is there a way to write 1 branch per event, instead of writing the entire tree over again each time? I want to end up with a tree with a number of branches corresponding to the number of events run.

At each eevent you should not do:

f->cd(); tree->Branch("Event", "TEvent", &event, 64000, 99); tree->Fill(); f->Write();
This creates a new branch for each event and writes the tree header
to the file. Instead you should do:

at initialisation time

f = new TFile("output.root", "RECREATE"); tree = new TTree("tree", "Data"); tree->Branch("Event", "TEvent", &event, 64000, 99);
for each event:

tree->Fill();
at the end of the job:

tree->AutoSave();
Rene