Anonymous user
Compound data type: Difference between revisions
→{{header|Visual Basic .NET}}: Expanded remarks about structure mutability
No edit summary |
(→{{header|Visual Basic .NET}}: Expanded remarks about structure mutability) |
||
Line 2,192:
=={{header|Visual Basic .NET}}==
===
▲<lang vbnet>Structure Simple_Point
Public X, Y As Integer
End Structure</lang>
Line 2,202 ⟶ 2,201:
=== 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.
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.
<lang vbnet>Structure Immutable_Point▼
Private m_X 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.
Public Sub New(ByVal x As Integer, ByVal y As Integer)▼
m_X = x▼
m_Y = y▼
End Sub▼
Below is the same <code>Point</code> as above, except with an immutable API.
ReadOnly Property X As
▲ End Sub
End Structure</lang>
|