在上一篇文章中,我們之前對BarChart.lerp的定義并不是高效的,我們正在創(chuàng)建的Bar實(shí)例,僅作為Bar.lerp的參數(shù)給出,并且針對動(dòng)畫參數(shù)t的每個(gè)值重復(fù)出現(xiàn)。每秒60幀,這意味著可能很多Bar實(shí)例被送到垃圾收集器,即使是相對較短的動(dòng)畫。
我們可以采用以下三種解決方案:
綜合考慮之下,我們使用最后一種解決方案,首先我們需要更新BarChart的部分代碼。
class BarChart { // ... static BarChart lerp(BarChart begin, BarChart end, double t) { final barCount = max(begin.bars.length, end.bars.length); final bars = new List.generate( barCount, (i) => Bar.lerp(begin._barOrNull(i), end._barOrNull(i), t) ); return new BarChart(bars); } // ...}
然后我們還需要更新一下Bar的條件邏輯。
class Bar { Bar(this.x, this.width, this.height, this.color); final double x; final double width; final double height; final Color color; static Bar lerp(Bar begin, Bar end, double t) { if(begin == null && end == null) return null; return new Bar( lerpDouble((begin??end).x, (end??begin).x, t), // ?:變量可以為null lerpDouble(begin?.width, end?.width, t), lerpDouble(begin?.height, end?.height, t), Color.lerp((begin??end).color, (end??begin).color, t) ); }}
現(xiàn)在我們的應(yīng)用程序里,如何將使用折疊的條形作為不可見元素的判斷,寫在Bar.lerp的條件邏輯中,實(shí)現(xiàn)我們想要的高效率。換一個(gè)角度來看,不知道大家有沒有發(fā)現(xiàn),現(xiàn)在代碼的可維護(hù)性已經(jīng)不如上一個(gè)版本了。這就是為什么之前選擇看起來效率較低的解決方案。在性能與可維護(hù)性之間選擇,需要通過衡量之后再作出決定。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持VEVB武林網(wǎng)。
新聞熱點(diǎn)
疑難解答