TFile read objects: deletion of TFile pointer is really slow


Please read tips for efficient and successful posting and posting code

_ROOT Version: 6.22
Platform: Not Provided
Compiler: Not Provided


Dear experts,
I would like to know if when using inputFile->GetList()->Clear(); it introduces a memory leak.

Because I have files with lot of histograms (approx 100M)
and want to select only some TH1D histograms from there
and when I delete the file pointer
it takes a lot of time because I think it is also deleting the TKeys and TObject entries that were read

So instead what I do is use the code below and it is way faster when calling inputFile->GetList()->Clear();
but I would like to know if there is no memory leak doing so,

Thanks in advance

#include<iostream>
#include<string> 
#include<vector> 

#include "TKey.h" 
#include "TObject.h" 
#include "TFile.h" 


int main()
{ 
  std::string filename = "" ; 

  TKey    *key       = nullptr ;
  TObject *obj       = nullptr ; 
  TFile   *inputFile = nullptr ; 
  
  filename = "/eos/user/b/bouquet/myfile.root" ; 

  inputFile = TFile::Open(filename.c_str()) ; 
  
  int count = 0 ; 
  TIter nextkey(inputFile->GetListOfKeys());
  while ((key = (TKey*)nextkey()))
  {
    obj = key->ReadObj(); 
    count += 1 ; 

    if (count % 1000== 0 )
    {
      std::cout << "count = " << count << std::endl ; 
    }
    //std::cout << obj->IsA()->GetName() << std::endl ;

    delete key ; 
    delete obj ;  
  }

  inputFile->GetList()->Clear();
  delete inputFile ; 

  return 0 ; 
}

@pcanal could you please take a look? Thank you in advance!

It does introduce a potential memory leak … more specifically, this does not delete the content, it just forgets it.

Because I have files with lot of histograms (approx 100M)
and want to select only some TH1D histograms from there
and when I delete the file pointer

Given this pattern, this means that you are also taking ownership of the histogram. The simplest solution is to “just” do:

histo->SetDirectory(nullptr);

This will indirectly remove the pointer from the list and thus, if you do this for all the histogram, the list will always be empty (and thus the deletion of the TFile will be fast).

Cheers,
Philippe.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.