Optimize graphExists function