Sometimes you have to manage memory in PHP

I’m currently working on a Google maps based project for a client, which deals with large numbers of points and overlays. At one point in the program I was getting around 16,000 Lat/Lng points from the database, which formed 70 polygons. Before the polygons could be rendered on Google Maps, I needed to group the points by polygon in an array. Originally I was using the following foreach loop to put the points into a polygons array:


	foreach($points as $point)
	{
		$polygons[$point->polygon_id][] = array(
			'lat'=>$point->lat,
			'lng'=>$point->lng,
			'order'=>$point->order
		);
	}

 

The problem was that when trying to render all 16,000 points, PHP was running out of memory. The reason was the entire 16,000 item array was being duplicated. I solved this issue by using array_shift instead of foreach to effectivly remove an item from the points array as I put it into the polygons array:


	while($point = array_shift($points))
	{
		$polygons[$point->polygon_id][] = array(
			'lat'=>$point->lat,
			'lng'=>$point->lng,
			'order'=>$point->order
		);
	}

 

I found it quite interesting that I having to (sort of) manage memory in a language with garbage collection, and reminded me why sometimes having to manage memory yourself, like in objective C, can be a good thing.

Thought I’d share my experience.

- MB

Posted in: Programming by Matt Bearman on 2nd December 2011 at 3:53 pm
Tags: , , ,

No Responses to “Sometimes you have to manage memory in PHP” - (Leave a comment)

No comments yet.

RSS | TrackBack URL

Leave a comment