Filtering FASTQ file based on read names from other file (how to increase performance) Python
Do not reinvent the wheel. There are bioinformatics tools that accomplish this task.
To extract reads from fastq files by IDs, use seqtk subseq.

Extract sequences with names in file name.lst, one sequence name per line:
seqtk subseq in.fq name.lst &gt; out.fq

It works with fasta files as well.
Use conda install seqtk or conda create --name seqtk seqtk to install the seqtk package, which has other useful functionalities as well, and is very fast.
Alternatively, use BBMap filterbyname.sh, see docs:

By default, &quot;filterbyname&quot; discards reads with names in your name list, and keeps the rest. To include them and discard the others, do this:
filterbyname.sh in=003.fastq out=filter003.fq names=names003.txt include=t

SEE ALSO:
Extracting specific sequences from FASTQ using Seqtk
How To Extracting Fastq Sequence For Given Fastq Ids And Fastq File
How To Extract A Subset Of Reads In Fastq Using An Id List?