compiler construction - What are best practices for arithmetic overflow checking in C#? -
there articles on web / stackoverflow usage of 'checked' keyword vs. compiler option 'check arithmetic overflow/underflow', those:
http://www.codethinked.com/c-trivia-what-no-overflow
why doesn't c# use arithmetic overflow checking default?
best way handle integer overflow in c#?
still don't know 1 should use. per default prefer go compiler option safe, not clutter code unchecked keyword, not forget in places , not commonly used, unknown many developers.
but how bad actual performance hit take? guess ms set default not overflow checking reason. compiler option concern code or every consumed libraries , framework itself?
i had same question. prefer piece of code checked default in company's code, because overflow side effects can cost lot , hard diagnose. discovering real reason of side effects can every valuable.
the question is, lose in terms of performance?
here simple bench :
static void main(string[] args) { long c = 0; var sw = new stopwatch(); sw.start(); unchecked { (long = 0; < 500000000; i++) c += 1; } sw.stop(); console.writeline("unchecked: " + sw.elapsedmilliseconds); c = 0; sw.restart(); checked { (long = 0; < 500000000; i++) c += 1; } sw.stop(); console.writeline("checked: " + sw.elapsedmilliseconds); }
in generated il, see checked , unchecked keyword determines whether add.ovf or add instruction used. (both debug , release configs)
il_001c: ldloc.2 il_001d: ldc.i4.1 il_001e: conv.i8 il_001f: add il_0066: ldloc.2 il_0067: ldc.i4.1 il_0068: conv.i8 il_0069: add.ovf
results (x64 host)
debug
- unchecked: 2371
- checked: 2437
release
- unchecked: 2088
- checked: 2266
other results replacing long(s) int(s) (x64 host)
debug
- unchecked: 1665
- checked: 1568
release
- unchecked: 189
- checked: 566
the performance hit there, looks more important choose right variable type go checked or unchecked. anyway doesn't change opinion. i'll turn on "check arithmetic overflow/underflow" in our projects! (advanced build settings).
when in need of performance, i'll use unchecked block.
Comments
Post a Comment