Fix quadratic dependency in QuantumCircuit.add_bits
#11546
Merged
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Summary
This is in the Python space component only. When
add_bits
is called many times, it constructs as temporary set of the union of all qubits and clbits present in the circuit in order to calculate an intersection with the input. This causes the method to be linear in the number of bits already present in the circuit, whereas it should be amortised linear in the to be added.This commit fixes the intersection to be a manual calculation that does not construct three temporary set objects, removing the quadratic cost.
Details and comments
This has been around for ages, but I noticed it when seeing excessive runtimes for parsing OQ2 and OQ3 programs constructed as
Adding jillions of registers is still quadratic in the number of registers because there's no constant-time lookup for them in
QuantumCircuit
(still), but that's a known problem.