File tree 1 file changed +17
-1
lines changed
crates/bindings-csharp/BSATN.Runtime/BSATN
1 file changed +17
-1
lines changed Original file line number Diff line number Diff line change @@ -50,9 +50,25 @@ public interface IReadWrite<T>
50
50
public readonly struct Enum < T > : IReadWrite < T >
51
51
where T : struct , Enum
52
52
{
53
+ private static readonly ulong NumVariants ;
54
+
55
+ static Enum ( )
56
+ {
57
+ NumVariants = ( ulong ) Enum . GetValues ( typeof ( T ) ) . Length ;
58
+ }
59
+
53
60
private static T Validate ( T value )
54
61
{
55
- if ( ! Enum . IsDefined ( typeof ( T ) , value ) )
62
+ // Previously this was: `if (!Enum.IsDefined(typeof(T), value))`.
63
+ // This was quite expensive because:
64
+ // 1. It uses reflection
65
+ // 2. It allocates
66
+ // 3. It is called on each row when decoding
67
+ //
68
+ // However, enum values are guaranteed to be sequential and zero based.
69
+ // Hence we only ever need to do an upper bound check.
70
+ // See `SpacetimeDB.Type.ParseEnum` for the syntax analysis.
71
+ if ( Convert . ToUInt64 ( value ) >= NumVariants )
56
72
{
57
73
throw new ArgumentOutOfRangeException (
58
74
nameof ( value ) ,
You can’t perform that action at this time.
0 commit comments