Compound data type: Difference between revisions
Content added Content deleted
No edit summary |
(→{{header|Visual Basic .NET}}: Expanded remarks about structure mutability) |
||
Line 2,192: | Line 2,192: | ||
=={{header|Visual Basic .NET}}== |
=={{header|Visual Basic .NET}}== |
||
=== |
=== Structures === |
||
A simple structure with two public, mutable fields: |
|||
⚫ | |||
⚫ | |||
Public X, Y As Integer |
Public X, Y As Integer |
||
End Structure</lang> |
End Structure</lang> |
||
Line 2,202: | Line 2,201: | ||
=== Immutable Structures === |
=== Immutable Structures === |
||
It is generally recommended in .NET that mutable structures only be used in niche cases where they provide needed performance, e.g. when the creation of massive numbers of class instances would cause excessive garbage collection pressure, as high-performance code dealing with structs generally is of a paradigm considered "impure" from an object-oriented perspective that relies on passing by reference and directly exposing fields. |
|||
In Visual Basic, mutable strucutures are difficult to use properly and should only be used when performance measurements warrant it. The rest of the time, immutable structures should be used. Below is the same structure seen before, but in an immutable form. |
|||
The semantics of value types in .NET mean that a new copy of a structure is created whenever one is passed by value to or from a method or property. This is particularly vexing when properties are involved, as it is not possible to mutate a structure that is returned by a property, due to the returned structure actually being an independent copy of whatever the property originally returned. The only workaround would be to store the value of the property in a temporary variable, mutate that variable, and assign the mutated variable back to the property, which involves another copy operation. When a structure is large, this copying can significantly affect performance. |
|||
⚫ | |||
⚫ | |||
Private m_Y As Integer |
|||
On another note, algorithms relying on immutable data structures are often more easily parallelized, as they eliminate the race conditions caused by concurrent reading and writing. |
|||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
Below is the same <code>Point</code> as above, except with an immutable API. |
|||
Public ReadOnly Property X() As Integer |
|||
Get |
|||
Return m_X |
|||
End Get |
|||
End Property |
|||
⚫ | |||
Public ReadOnly Property Y() As Integer |
|||
ReadOnly Property X As Integer |
|||
⚫ | |||
Return m_Y |
|||
End Get |
|||
End Property |
|||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
End Structure</lang> |
End Structure</lang> |
||