如何修复XML内存“泄漏”

处理XML文件,可以很容易引起Flash内存“泄漏”。你的应用程序可能只保留XML文件内容的一小部分,但整个文件可能会留在内存中,从来没有垃圾回收。今天的文章中讨论这是如何发生的,以及如何清理所有未使用的内存。

这种特殊的内存“泄漏”源于一个奇特的行为,在Flash中构建其他字符串的字符串实际上并不拥有一份原始字符串的字符。相反,它们有一个“主字符串”字段引用原始字符串中的字符。在调试版本的Flash Player,你可以看到“主字符串”使用flash.sampler.getMasterString的内容。请看下面的例子:

1 var str:String = "ABCDEFGHIJKLMNOPQRSTUV".substr(0,2);
2 trace(str + " has master string " + flash.sampler.getMasterString(str));
3 // output: AB has master string ABCDEFGHIJKLMNOPQRSTUV 

“AB”构建后,即使你只使用“AB”字符串,Flash仍会在内存中持有整个“ABCDEFGHIJKLMNOPQRSTUV”字符串。虽然少数的英文字母没什么影响,但当你处理庞大的XML文件时,这个问题将难以控制。如果你做的是从XML中取一个字符串赋值给变量?事实证明,在这种情况下,整个XML文件会留在内存中。为了说明问题,这里有一个小例子:

1 var xml:XML = new XML(
2         '<people><person first="John"/><person first="Mary"/></people>'
3 );
4 xmlJohn = xml.person[0].@first;
5 trace(xmlJohn + " has master string " + flash.sampler.getMasterString(xmlJohn));
6 // output: John has master string <people><person first="John"/><person first="Mary"/></people> 

JSON呢?同样的问题是否也有发生?幸运的是,它不会:

1 var json:Object = JSON.parse(
2         '{"people":[{"first":"John"},{"first":"Mary"}]}'
3 );
4 jsonJohn = json.people[0].first;
5 trace(jsonJohn + " has master string " + flash.sampler.getMasterString(jsonJohn));
6 // output: John has master string null 

所以,你会如何清理XML文件里中的所有主字符串负担?为了解决这个问题,我创建了一个修改字符串的静态函数就能够使Flash Player清除主字符串。随意用在自己的项目中:

 1 /**
 2 *   Replace a string's "master string"-- the string it was built from-- with a single
 3 *   character to save memory.
 4 *   @param str String to clean
 5 *   @return The input string, but with a master string only one character larger than it
 6 *   @author JacksonDunstan.com/articles/2260
 7 */
 8 public static function cleanMasterString(str:String): String
 9 {
10         return ("_"+str).substr(1);
11 } 

字符串 用了这个函数后将被简化为“_John”.

最后,我创建了一个简单的示例程序,以测试XML,JSON字符串使用上述函数清理XML中的字符串。你需要一个调试版本的Flash Player来运行它,因为它使用flash.sampler.getMasterString

 

原文链接: 如何修复XML内存“泄漏”

原文链接:http://jacksondunstan.com/articles/2260

原文地址:https://www.cnblogs.com/atong/p/3116544.html