Menu

My Struct Update Copied 64 Bytes Twice
πŸ“°

My Struct Update Copied 64 Bytes Twice

DEV Community: dotnetΒ·Sukhpinder SinghΒ·6 days ago
#S2cJVFPT
#devtodotnet#devto#dev#list#double
Reading 0:00
15s threshold

I had a physics step that walked a List<Body> every frame and nudged each body's position by its velocity. Simple loop, nothing exotic. And the profiler kept pointing at it with more weight than three lines of double addition had any right to carry. The arithmetic wasn't the problem. The copies were.

Here's the thing I'd forgotten. When you index into a List<T> of structs, you don't get the element. You get a copy of it. So this doesn't even compile:

world [ i ]. X += world [ i ]. Vx ;

Enter fullscreen mode

Exit fullscreen mode

The compiler stops you cold:

error CS1612: Cannot modify the return value of 'List<Body>.this[int]' because it is not a variable

Enter fullscreen mode

Exit fullscreen mode

Which is actually the compiler being honest. If it let you write that, you'd be mutating a throwaway copy and the real element would sit there unchanged, and you'd spend an afternoon wondering why your bodies never move.…

Continue reading β€” create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.