我目前正在使用GoLang创建一个游戏。我正在测量FPS。我注意到在使用for循环将内容附加到切片时,会损失约7个FPS,例如:
vertexInfo := Opengl.OpenGLVertexInfo{}
for i := 0; i < 4; i = i + 1 {
vertexInfo.Translations = append(vertexInfo.Translations, float32(s.x), float32(s.y), 0)
vertexInfo.Rotations = append(vertexInfo.Rotations, 0, 0, 1, s.rot)
vertexInfo.Scales = append(vertexInfo.Scales, s.xS, s.yS, 0)
vertexInfo.Colors = append(vertexInfo.Colors, s.r, s.g, s.b, s.a)
}
我对每个精灵、每个绘制都执行此操作。问题是,为什么我只是循环几次并将相同的内容附加到这些切片中,却会出现如此巨大的性能损失?有没有更有效的方法来做到这一点?并不像我添加了过多的数据。每个切片包含约16个元素,如上所示(4 x 4)。
当我简单地将所有16个元素放在一个
[]float32{1..16}
中时,fps提高了约4。更新:我对每个附加进行了基准测试,似乎每个附加需要1 fps才能执行。考虑到这些数据非常静态,这似乎是很多...我只需要4次迭代...
更新:添加了github repo https://github.com/Triangle345/GT
type Vec3 struct { X, Y, Z float32 }; type Vec4 struct { X, Y, Z, W float32 }; type Color struct { R, G, B, A byte }
然后您有type VertexInfo { Translations, Scales [4]Vec3; Rotations [4]Vec4; Colors [4]Color }
(或者如果都一样,可以删除内部数组并使用[4]VertexInfo
)。 - twotwotwosync.Pool
进行回收,或者如果您有多余的RAM,则可以使用runtme.SetGCPercent
来更少频繁地触发GC以换取更多的RAM也会有所帮助。 - twotwotwoa=a[:0]
将一个切片设为零长度和非零容量——如果下一帧中切片长度相同,则不会重新分配。 - chill