martindevans / SupersonicSound

C# Wrapper For FMOD Studio
Other
29 stars 9 forks source link

Discuss: What are the benefits of using structs vs classes? #15

Closed HakanL closed 9 years ago

HakanL commented 9 years ago

For example in my app I want to keep a reference to the current playing channel and stop it before playing a new sound. Since the Channel (in SSS) is a struct that means I can't check on null and calling Stop() will not work since it's not actually assigned to a FMOD-channel. The memory overhead for a class vs struct is literally 4 bytes so can't see that it would be a deciding factor, IMHO.

martindevans commented 9 years ago

The cost of classes is garbage collection, rather than memory overhead. GC latency causing stuttering can be a serious problem in games, and I didn't want SSS to contribute any further to this problem.

Unfortunately the underlying wrapper does use classes - if SSS wrapped these classes in additional classes we'd be making a lot of garbage!

Could you show me some example code for what exactly you can't do? So far I haven't encountered anything I can't do with SSS, if you can provide a good counter example I can try to find a workaround.

HakanL commented 9 years ago

I just don't see that the tiny classes in SSS would affect stuttering due to GC much, but I don't have much experience on the other hand with audio apps. There won't be 1000s of these classes anyway, even if SSS were to use classes. It's just a little cleaner in C# to deal with references/classes.

I have a property that holds the current playing channel. When I get a request to play a new sound I want to stop the current playing sound first, so if it's set I just call Stop() before I play a new sound. The workaround is to check if Channel.FModChannel is null, but it's a little clunky and I'd prefer to never access the FMod-properties in the consuming app.

https://gist.github.com/HakanL/06f1cb5040334adea89f

HakanL commented 9 years ago

I guess I can make my properties Nullable<> but I wanted to see what the reasoning for structs were, in the past I've seen where it's been used for the wrong reasons.

martindevans commented 9 years ago

Ah I see what you mean from your example - using nullables is what I had in mind for this situation. WIth C# 6 it's very ergonomic to do so:

_channel?.Stop()

It's not really the size of objects which matters for GC, it's the number and how long they live. With SSS we could potentially create a lot of objects which live a long time - a pretty nasty combination! I agree it's not perfect, but I really want supersonic sound to be a zero cost abstraction over the normal FMOD API and structs are the only way to achieve zero cost.

HakanL commented 9 years ago

I have to start using C# 6 :)

I understand where you're coming from now, makes sense, thanks!