This is usually in regards to sounds.
Let’s say I make a gun and everytime it fires, a sound plays. I then wonder wether I should create a new sound every time with Instance.new (on client) or just put a permanent sound object in the gun and make it play whenever activated.
Which is better performance wise and in what situation would you choose the one over the other?
Rehuse a single instance is always the best performance-wise. Creating a new instance each time a sound should play could not be the best idea. At least thats what I think
Hey, Both approaches can be appropriate depending on the situation, but they do have some performance implications:
Creating a New Sound Instance Each Time:
Creating a new sound instance with Instance.new each time the gun fires can give you a lot of flexibility, such as if you want to play different sound effects for different types of gunfire or different environmental conditions. This can make the sounds feel more dynamic and varied, which can help to enhance the game’s immersion. However, this approach can also create more load on the client, as each sound instance takes up memory and processing power. This may lead to performance issues if the gun is fired frequently or if there are many guns firing at the same time.
Using a Permanent Sound Object:
Using a permanent sound object and simply playing it whenever the gun is fired is a more efficient approach from a performance perspective. Because the sound object is created once and reused, it uses less memory and processing power than creating a new sound object each time. This approach is suitable when the sound effect is always the same and doesn’t need to vary based on different conditions.
So, to summarize, if performance is a concern and the sound effect doesn’t need to change, then using a permanent sound object would be a better choice. However, if you want more flexibility and variation in your sound effects, and you’re not too concerned about the performance impact, then creating a new sound instance each time could be a better option.
If you opt for creating a new instance each time, remember to clean up (i.e., remove) the instances once they’ve finished playing to avoid memory leaks.
You could also consider a hybrid approach: have a pool of pre-created sound instances and recycle them. This gives you the flexibility of different sounds while avoiding the cost of constantly creating and destroying instances.