Variable Declaration inside infinite loop

218 views
Skip to first unread message

Shashwat

unread,
Jan 25, 2023, 12:07:02 PM1/25/23
to golang-nuts
Is it safe to declare a variable inside an infinite loop ?

for {
    a := 0
    a += 1
}

Won't this cause memory allocation in every iteration ?

As the declared variables will be allocated memory in the stack and not heap memory, so garbage collector can't clear the allocated memory, and eventually process will be terminated, isn't it?

Jakob Borg

unread,
Jan 25, 2023, 2:54:45 PM1/25/23
to Shashwat, golang-nuts
No. Apart from compiler optimisations, consider that the variable goes out of scope at the end of each iteration.

//jb

Roland Müller

unread,
Jan 26, 2023, 11:16:04 AM1/26/23
to golang-nuts
In Java this may cause memory fragmentation when the amount of allocated memory varies and the variables use much memory.

Dont know whether this may occur in Go too.

- Roland

> //jb
>
> --
> You received this message because you are subscribed to the Google Groups "golang-nuts" group.
> To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
> To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/CE4EFF63-BD16-46F8-96EF-69000F7D9ACD%40kastelo.net.
>

Robert Engels

unread,
Jan 26, 2023, 11:25:31 AM1/26/23
to Roland Müller, golang-nuts
Java would no-op that entire loop since it does nothing that is externally visible. 

On Jan 26, 2023, at 9:30 AM, Roland Müller <rol...@gmail.com> wrote:



Ian Lance Taylor

unread,
Jan 26, 2023, 11:27:17 AM1/26/23
to Roland Müller, golang-nuts
On Thu, Jan 26, 2023, 8:15 AM Roland Müller <rol...@gmail.com> wrote:


Am Mittwoch, 25. Januar 2023 schrieb 'Jakob Borg' via golang-nuts <golan...@googlegroups.com>:
> On 25 Jan 2023, at 12:26, Shashwat <qa80...@gmail.com> wrote:
>>
>> Is it safe to declare a variable inside an infinite loop ?
>>
>> for {
>>     a := 0
>>     a += 1
>> }
>>
>> Won't this cause memory allocation in every iteration ?
>>
>> As the declared variables will be allocated memory in the stack and not heap memory, so garbage collector can't clear the allocated memory, and eventually process will be terminated, isn't it?
>
> No. Apart from compiler optimisations, consider that the variable goes out of scope at the end of each iteration.
>

In Java this may cause memory fragmentation when the amount of allocated memory varies and the variables use much memory.

Dont know whether this may occur in Go too.

Not for a program like above, which will be entirely stack allocated.

Ian
Reply all
Reply to author
Forward
0 new messages