performance - Attempt to "go back" without goto statement -


the code examples gonna in lua, question rather general - it's just example.

for k=0,100      ::again::     local x = math.random(100)      if x <= 30          --     else         goto again            end  end 

this code generates 100 pseudorandom numbers between 0-30. should between 0-100, doesn't let loop go on if of them larger 30.

i try task without goto statement.

for k=0,100      local x = 100 -- may put behind "for", in cases, matter need 'x' variable      while x >= 30 --important! it's opposite operation of "if" condition above!          x = math.random(100)      end      -- same "something" in condition above   end 

instead, program runs random number generation until desired value. in general, put codes here between main loop , condition in first example.

theoretically, same first example, without gotos. however, i'm not sure in it.

main question: these program codes equal? same? if yes, faster (=more optimized)? if no, what's difference?

it bad practice use goto. please see http://xkcd.com/292/

anyway, i'm not lua, looks simple enough;

for first code: doing starting loop repeat 100 times. in loop make random number between 0 , 100. if number less or equal 30, it. if number greater 30, throw away , random number. continues until have 100 random numbers less or equal thirty.

the second code says: start loop 0 100. set x 100. start loop condition: long x greater 30, keep randomizing x. when x less 30 code exit , perform action. when has performed action 100 times, program ends.

sure, both codes same thing, first 1 uses goto - bad practice regardless of efficiency.

the second code uses loops, still not efficient - there 2 levels of loops - , 1 based on psuedo-random generation can extremely inefficient (maybe cpu generates numbers between 30-100 trillion iterations?) things slow. true you're first piece of code - has 'loop' based on psuedo-random number generation.

tldr; strictly speaking efficiency, not see 1 of being more efficient other. wrong seems same things going on.


Comments

Popular posts from this blog

assembly - 8086 TASM: Illegal Indexing Mode -

Java, LWJGL, OpenGL 1.1, decoding BufferedImage to Bytebuffer and binding to OpenGL across classes -

javascript - addthis share facebook and google+ url -