I am currently looking at this:
This is some adapted code:
struct Chromosome
{
public bool[] genes;
public int fitness;
}
I have never used structs in my evolutionary algorithms/genetic algorithms. Is it not a bit pointless to use arrays in structs – especially when I have to make deep copies? Is there any advantage of using structs in this scenario?
Thanks.
Typically, we use a
structto represent something that can be considered pretty primitive. According to MSDN, it should be a type that represents a single “value”, 16 bytes or less in size, and so on.The main thing to keep in mind with a
structis the value-type semantics, so passing this in and out of functions will create a copy. Cost wise this won’t be too bad since what you are copying is 1 reference (to the array of bool) and 1 int, but it does create some interesting side effects if you try to modify the array reference in another method or from a copy.Many people assume
structwill always be more efficient thanclass, but this is not always the case and usually this micro-optimization is more dangerous than helpful because it introduces the side-effects of working with a value type.As for the array of
boolyou can either create and set bits in anintor use theBitArrayspecialized class in the BCL.So, the long and the short of it is, if this is legacy code and you want to keep the
struct, it will work, but it can byte you if you expect it to act like aclassdoes when passed/copied. However, looking at what it’s holding, it doesn’t meet the MSDN guidance for whatstructis best suited for.