c# - Do unnecessary curly braces reduce performance? -
after encountering while programming, have been wondering this. below 2 snippets both legal , compile. specifically, question this.. in second case, brackets make program slower? why allowed?
1st case:
if (statement) { // }
2nd case:
{ if (statement) { // } }
additionally if had code below.. runtime same calling function x without of curly brackets.
{ { { // call function x } } }
most of time doesn't make difference - , should code readability more else.
however, curly braces can have effect on performance, in surprising way, although it's pretty unusual. consider code:
using system; using system.collections.generic; class test { static void fewercurlies() { list<action> actions = new list<action>(); (int = 0; < 100; i++) { int x; if (i % 3 == 0) { actions.add(() => x = 10); } int y; if (i % 3 == 1) { actions.add(() => y = 10); } } } static void morecurlies() { list<action> actions = new list<action>(); (int = 0; < 100; i++) { { int x; if (i % 3 == 0) { actions.add(() => x = 10); } } { int y; if (i % 3 == 1) { actions.add(() => y = 10); } } } } }
the braces in morecurlies
redundant, right? not quite... generated code looks more this:
using system; using system.collections.generic; class test { static void fewercurlies() { list<action> actions = new list<action>(); (int = 0; < 100; i++) { fewercurliescapture capture = new fewercurliescapture(); if (i % 3 == 0) { actions.add(capture.method1); } if (i % 3 == 1) { actions.add(capture.method2); } } } static void morecurlies() { list<action> actions = new list<action>(); (int = 0; < 100; i++) { { morecurliescapture1 capture = new morecurliescapture1(); if (i % 3 == 0) { actions.add(capture.method); } } { morecurliescapture1 capture = new morecurliescapture2(); if (i % 3 == 1) { actions.add(capture.method); } } } } private class fewercurliescapture { public int x; public int y; public void method1() { x = 10; } public void method2() { y = 10; } } private class morecurliescapture1 { public int x; public void method() { x = 10; } } private class morecurliescapture2 { public int y; public void method() { y = 10; } } }
the differences here are:
- an instance of capture class created in each iteration of loop in
fewercurlies
, if it's not used - each instance of capture class used in
fewercurlies
contains both variables, though each delegate use 1 of them, whereas inmorecurlies
each capture class captures single variable
this implementation-specific, shows redundant-looking curlies can have impact.
Comments
Post a Comment