Difference between declaring variables before or in loop?

前端 未结 25 2067
长发绾君心
长发绾君心 2020-11-22 02:37

I have always wondered if, in general, declaring a throw-away variable before a loop, as opposed to repeatedly inside the loop, makes any (performance) difference? A (q

25条回答
  •  有刺的猬
    2020-11-22 03:26

    Well I ran your A and B examples 20 times each, looping 100 million times.(JVM - 1.5.0)

    A: average execution time: .074 sec

    B: average execution time : .067 sec

    To my surprise B was slightly faster. As fast as computers are now its hard to say if you could accurately measure this. I would code it the A way as well but I would say it doesn't really matter.

提交回复
热议问题