Merging of two root files

This is not actually a root problem, but as I’m using root to merge the data, I’m posting my problem here.
I’ve two root files in tree e.g.: [color=blue]file1.root[/color] and [color=blue]file2.root[/color]
For merging I need to match the events in both files and then make a new file [color=blue]newfile.root[/color] with the same data.
The contents in [color=blue]file1.root[/color] and [color=blue]file2.root[/color] are e.g.
[color=red]
sp1 ev1 a1 b1 || sp2 ev2 c1 d1
1 1 20 21 || 1 2 11 13
1 2 12 14 || 1 4 10 15
1 4 10 11 || 1 5 12 16

[/color]

I check the sp1,ev1,sp2,ev2 and then make newfile.root.
The code is ,
for (Int_t i = 0; i<nentries1; i++) {
nb1 = inTr1->GetEntry(i); [color=red]\file1.root entry[/color]
for (Int_t j=0; j<nentries2; j++){
nb2 = inTr2->GetEntry(j); [color=red]\file2.root entry[/color]

 [color=red] // Check the sp and ev for both input files[/color]
  if(sp1 != sp2 || ev1 != ev2 )continue;

Spill =sp1;
Event = ev1;
Flag =a1 ;

}
}

[color=red]Problem : [/color]Each files has events e.g. 1millions, so the total loop event becomes 1M*1M, as u can see from the code. Then the total time for merging becomes very large, like few days.
Is there a better way to merge the files with less time ?
Thank you.

see TTree::BuildIndex

Rene