我试图在React Native中建立一个移动池游戏,0.17,用于体验并遇到有关垃圾收集的问题。现在我有十个同时渲染的圆圈在屏幕上反弹。但是,应用程序的内存消耗随着时间的推移而增加,我不知道如何解决这个问题。
在早期版本中,这似乎是一个React Native问题,我确实注意到内存会随着时间的推移而下降,如图中所示,但是在更大的应用程序中,我担心这可能是个问题。还有其他人有类似的问题或有解决方案吗?
相关代码在这里,非常感谢任何帮助。谢谢!
var Test = React.createClass({
getInitialState: function() {
var circs = [];
for (var i = 0; i < startCount; i++) {
circs.push({
id: i,
x: 0,
y: 0,
vx: 2 + Math.random() * 2,
vy: 2 + Math.random() * 2,
dx: 0,
dy: 0,
cOb: new Animated.ValueXY({x: 0, y: 0}),
});
}
return {
circles: circs,
stop: 1
};
},
stopCircle: function() {
this.state.stop = -1 * this.state.stop;
this.setState(this.state);
},
componentDidMount: function() {
this.animateCircles();
},
animateCircles: function() {
this.triggerAnimation(this.animateCircles);
},
triggerAnimation: function(ani) {
for (var i = 0; i < this.state.circles.length; i++) {
var cCircle = this.state.circles[i];
if (cCircle.x * cCircle.x + cCircle.y * cCircle.y > DIST_TO_EDGE * DIST_TO_EDGE) {
var prevX = cCircle.x - cCircle.vx;
var prevY = cCircle.y - cCircle.vy;
var exitX = (1.5 * prevX + .5 * cCircle.x) / 2;
var exitY = (1.5 * prevY + .5 * cCircle.y) / 2;
cCircle.x = prevX;
cCircle.y = prevY;
var exitRad = Math.sqrt(exitX * exitX + exitY * exitY);
exitX = exitX * DIST_TO_EDGE / exitRad;
exitY = exitY * DIST_TO_EDGE / exitRad;
var twiceProjFactor = 2 * (exitX * cCircle.vx + exitY * cCircle.vy) / (DIST_TO_EDGE * DIST_TO_EDGE);
cCircle.vx = cCircle.vx - twiceProjFactor * exitX;
cCircle.vy = cCircle.vy - twiceProjFactor * exitY;
break;
}
}
if (this.state.stop == 1) {
for (var k = 0; k < this.state.circles.length; k++) {
this.state.circles[k].x += this.state.circles[k].vx;
this.state.circles[k].y += this.state.circles[k].vy;
}
}
this.setState(this.state);
var animateC = [];
for (var i = 0; i < this.state.circles.length; i++) {
var currCirc = this.state.circles[i];
animateC.push(
Animated.timing(currCirc.cOb, {
...TIMING_CONFIG,
toValue: {x: currCirc.x, y: currCirc.y}
}));
}
Animated.parallel(
animateC
).start(ani);
},
getStyle: function(which) {
return [
styles.circle,
{transform: this.state.circles[which].cOb.getTranslateTransform()}
];
},
render: function() {
return (
<View style={styles.container}>
<View style={styles.edge}>
</View>
{
this.state.circles.map(function(c, i) {
return (
<TouchableWithoutFeedback key={i} onPress={this.stopCircle}>
<Animated.View style={this.getStyle(i)} />
</TouchableWithoutFeedback>
);
}, this)
}
</View>
);
},
如果您想自己运行该应用程序,可以在https://github.com/heliumsoule/React-Native-Pool找到完整的应用程序。
再次感谢你。
答案 0 :(得分:0)
您有两个虚拟机,它们都按照自己的条件执行垃圾收集。 JVM和JavaScript。
这篇文章可能会帮到你:
http://moduscreate.com/dynamic-memory-and-v8-with-javascript/
另外,我建议您尽可能多地注释掉代码并查看对内存的影响。然后一次评论一下,看看哪个代码会导致你的内存消耗增长最快。