Write a function to detect cycles in a directed graph and explain how you would optimize it for large datasets.