optimized code for grids