mstefarov / fNbt

A C# library for reading and writing Named Binary Tag (NBT) files and streams. A continuation of libnbt project, originally by Erik Davidson (aphistic).
116 stars 31 forks source link

Remove the need for unsafe code #20

Closed AjaxGb closed 6 months ago

AjaxGb commented 8 years ago

Unsafe code was only used in three places in the NbtBinaryWriter class: once each to cast floats to uint bits and doubles to ulong bits, and once to use this method. I have changed the casting to make use of struct member overlap, and there is an almost identical method that uses safe code.

These changes should make compiling easier (they did for me).

mstefarov commented 8 years ago

Looks good! I'll check for performance impact of these changes, and merge it if there are no problems.

mstefarov commented 8 years ago

Alright, I did some profiling. Changes to Write(float) and Write(double) don't cause any problems, but changes to Write(string) cause a 25% increase in CPU time, as well as doubling the amount of heap allocation. That added value.ToCharArray() call is pretty expensive.

Under-the-hood in the .NET Framework, EncoderNLS.GetBytes(Char[]...) simply proxies to EncoderNLS.GetBytes(Char*...) anyway. Is there really a good reason not to stick to the current, "unsafe" but efficient implementation of NbtBinaryWriter?

mstefarov commented 8 years ago

fNbt Issue 20 profiling results in dotTrace

Here are the profiling results by the way, before/after.

AjaxGb commented 8 years ago

Nah, that sounds reasonable.

NiclasOlofsson commented 8 years ago

FYI, I just forked the project and had absolutely no problems getting it to compile.