(转)flex强制垃圾回收

时间:2016-7-21    作者:悬浮的青春    分类: gis二次开发


  1. package
  2. {
  3. import flash.display.Sprite;
  4. import flash.external.ExternalInterface;
  5. import flash.net.LocalConnection;
  6. public class MemeryGcTest extends Sprite
  7. {
  8. private const num:int = 30000; //子元素个数 根据自己的电脑配置来设置
  9. private var parentContainer:Sprite;//父容器
  10. private var childrenRect:Array;//所有子元素的引用
  11. public function MemeryGcTest(){
  12. init();
  13. }
  14. private function init() : void{
  15. parentContainer=new Sprite();
  16. addChild(parentContainer);
  17. createAllChildrens();
  18. removeAllchildrens();
  19. setChildrenNull();
  20. //doGc();
  21. }
  22. /**
  23. * 移除所有对象
  24. *
  25. */
  26. private function removeAllchildrens():void {
  27. removeAllChildrens( );
  28. removeChild(parentContainer);
  29. }
  30. /**
  31. * 设置不用对象为null 否则不会进行垃圾回收
  32. *
  33. */
  34. private function setChildrenNull():void{
  35. childrenRect = null;
  36. parentContainer = null;
  37. }
  38. /**
  39. * 创建所有子元素
  40. *
  41. */
  42. private function createAllChildrens() : void {
  43. childrenRect=new Array();
  44. for(var i:int = 0;i<num; i++){
  45. var sprite:Sprite=new Sprite();
  46. childrenRect.push(sprite);
  47. sprite.graphics.beginFill(0xff0000);
  48. sprite.graphics.drawRect(0+i/50,0,100,100);
  49. sprite.graphics.endFill();
  50. parentContainer.addChild(sprite);
  51. }
  52. }
  53. /**
  54. * 移除所有子元素
  55. *
  56. */
  57. private function removeAllChildrens():void{
  58. for(var i:int=0;i<num;i++){
  59. parentContainer.removeChild(childrenRect[i]);
  60. delete childrenRect[i];
  61. }
  62. }
  63. /**
  64. * 强制垃圾回收
  65. *
  66. */
  67. private function doGc():void{
  68. try{
  69. var conn1:LocalConnection= new LocalConnection();
  70. conn1.connect("testGc");
  71. var conn2:LocalConnection= new LocalConnection();
  72. conn2.connect("testGc");
  73. }catch(error:Error){
  74. conn1 = null;
  75. conn2 = null;
  76. }
  77. }
  78. }




设置回收需要事先将要回收的对象置空。设置为null。

WRITTEN BY

avatar