diff --git a/src/backend/postmaster/autovacuum.c b/src/backend/postmaster/autovacuum.c
index b745d89..1a32433 100644
*** a/src/backend/postmaster/autovacuum.c
--- b/src/backend/postmaster/autovacuum.c
*************** do_autovacuum(void)
*** 2444,2451 ****
  		 */
  		PG_TRY();
  		{
  			/* have at it */
- 			MemoryContextSwitchTo(TopTransactionContext);
  			autovacuum_do_vac_analyze(tab, bstrategy);
  
  			/*
--- 2444,2453 ----
  		 */
  		PG_TRY();
  		{
+ 			/* Use PortalContext for any per-table allocations */
+ 			MemoryContextSwitchTo(PortalContext);
+ 
  			/* have at it */
  			autovacuum_do_vac_analyze(tab, bstrategy);
  
  			/*
*************** do_autovacuum(void)
*** 2482,2487 ****
--- 2484,2492 ----
  		}
  		PG_END_TRY();
  
+ 		/* Make sure we're back in AutovacMemCxt */
+ 		MemoryContextSwitchTo(AutovacMemCxt);
+ 
  		did_vacuum = true;
  
  		/* the PGXACT flags are reset at the next end of transaction */
*************** perform_work_item(AutoVacuumWorkItem *wo
*** 2614,2619 ****
--- 2619,2627 ----
  
  	autovac_report_workitem(workitem, cur_nspname, cur_datname);
  
+ 	/* clean up memory before each work item */
+ 	MemoryContextResetAndDeleteChildren(PortalContext);
+ 
  	/*
  	 * We will abort the current work item if something errors out, and
  	 * continue with the next one; in particular, this happens if we are
*************** perform_work_item(AutoVacuumWorkItem *wo
*** 2622,2630 ****
  	 */
  	PG_TRY();
  	{
! 		/* have at it */
! 		MemoryContextSwitchTo(TopTransactionContext);
  
  		switch (workitem->avw_type)
  		{
  			case AVW_BRINSummarizeRange:
--- 2630,2639 ----
  	 */
  	PG_TRY();
  	{
! 		/* Use PortalContext for any per-work-item allocations */
! 		MemoryContextSwitchTo(PortalContext);
  
+ 		/* have at it */
  		switch (workitem->avw_type)
  		{
  			case AVW_BRINSummarizeRange:
*************** perform_work_item(AutoVacuumWorkItem *wo
*** 2668,2673 ****
--- 2677,2685 ----
  	}
  	PG_END_TRY();
  
+ 	/* Make sure we're back in AutovacMemCxt */
+ 	MemoryContextSwitchTo(AutovacMemCxt);
+ 
  	/* We intentionally do not set did_vacuum here */
  
  	/* be tidy */
