static void P(){ while(true){ int i = Console.Read(); bool b = i == 5; Console.WriteLine(i); Console.WriteLine(b); } } 静态无效Q(){ int i; bool b; while(true){ i = Console.Read(); b = i == 5; Console.WriteLine(i ); Console.WriteLine(b); } } } Using local declarations within a block often makes code more readable, butis it less efficient? eg...void P() {while (...) {int i = ...;bool b = ...;....}}At first sight this looks inefficient, because i and b are being allocatedeach time around the loop. But I wonder if that is really the case. I haveheard that when procedure P is placed on the stack, that *all* variableswithin P, including those within a nested scope, are also allocated. ie. inthe above example, i and b would be allocated only once, at the start of theprocedure. However, I am not sure whether this is the true.What if the the variable is nested within a conditional - is it still alwaysallocated at the start? eg...while (...) {if (...) {int i = ...;bool b = ...;....}}Any experts here who can ease my mind about the possible ineffiency ofnested variables?A bit of background - I''m writing a real time application, with severalcomplex loops processing data which is being received at a high rate, so Ikeep coming across this dilemna.TIA,Javaman 解决方案In the following, P() And Q() compile down to the exact same IL for me (andoptimization is *off*). You can try it yourself with ILDASM.using System;class Test{static void Main() {P();Q();}static void P() {while (true) {int i = Console.Read();bool b = i == 5;Console.WriteLine(i);Console.WriteLine(b);}}static void Q() {int i;bool b;while (true) {i = Console.Read();b = i == 5;Console.WriteLine(i);Console.WriteLine(b);}}} 这篇关于循环中的嵌套变量 - 效率低下?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
08-14 06:25