Skip to content

small refactoring to reduce memory usage #9078

Closed

Description

@Lslightly

The associated forum post URL from https://forum.rclone.org

This change is small and easy to apply I think.

What is your current rclone version (output from rclone version)?

v1.72.1

What problem are you are trying to solve?

Removing unnecessary heap allocation.

How do you think rclone should be changed to solve that?

Just move the location to declare variables.

  1. 3 variables in WaitForStateContext

notfoundTick := 0
targetOccurrence := 0

Currently, these variables will be allocated in heap, which consumes more memory. They are all used in go func() but not used in other places. So they can be declared in go func().

  1. change = to :=, which is a tiny change.

err = req.Reply(ok, reply)

Because of =, the assignment op, err variable declared in handleChannel will be allocated in heap, which is unnecessary. Change = to := to declare err in the function literal will avoid allocating it in heap. This is really a small change but it does work. 😂

How to use GitHub

  • Please use the 👍 reaction to show that you are affected by the same issue.
  • Please don't comment if you have no relevant information to add. It's just extra noise for everyone subscribed to this issue.
  • Subscribe to receive notifications on status change and new comments.

Activity

  1. changed the title [-]small refactoring to reduce heap allocation[/-] [+]small refactoring to reduce memory usage[/+] on Jan 5, 2026
  2. added a commit that references this issue on Jan 5, 2026
    509b811
  3. ncw commented on Jan 5, 2026

    @ncw
    Member

    You can see with

    go build -gcflags="-m" file.go
    

    Whether this actually makes a difference. The go compiler is quite capable of working out what escapes and what doesn't so that might be interesting to confirm your code changes are working.

  4. Lslightly commented on Jan 6, 2026

    @Lslightly
    ContributorAuthor

    The escape analysis log before changing is as follows. Only relevant lines are extracted here.

    $ go build -a -gcflags=all=-m=2 . &> m2.log
    $ rg -C 10 'backend/oracleobjectstorage/waiter.go:63' m2.log
    backend/oracleobjectstorage/waiter.go:63:2: moved to heap: notfoundTick
    backend/oracleobjectstorage/waiter.go:64:2: moved to heap: targetOccurrence
    backend/oracleobjectstorage/waiter.go:87:2: moved to heap: result
    $ rg 'cmd/serve/sftp/connection.go:254' m2.log
    cmd/serve/sftp/connection.go:254:21: moved to heap: err
    

    After changing, notfoundTick, targetOccurrence, result, err are allocated in stack.

    $ go build -a -gcflags=all=-m=2 . &> m2.log
    $ rg 'notfoundTick' m2.log # No output with return code 1
    $ rg 'targetOccurrence' m2.log # No output with return code 1
    $ rg 'backend/oracleobjectstorage/waiter.go:87' m2.log # No output with return code 1. In PR#9079, the line of new definition of `result` is 87. see https://github.com/rclone/rclone/pull/9079/changes#diff-d09350928b2530376c41a5714eedf5d9e2a2922fe250194f317900e3e07530a3R87
    $ rg 'cmd/serve/sftp/connection.go:254' m2.log # No output again. In PR#9079, the line of `err` definition does not change. You can see https://github.com/rclone/rclone/pull/9079/changes#diff-853a5af09efd80d0bfa2aa41c0ad00a48c3937258a3676780fc56e192c899cd9L254
    

    I think the log proves the tiny improvement.


    There is another variable whose type is pointer is allocated in heap and can be allocated in stack through code changing. But I don't change that in PR.

    rclone/backend/ftp/ftp.go

    Lines 883 to 903 in 28c187b

    func (f *Fs) List(ctx context.Context, dir string) (entries fs.DirEntries, err error) {
    // defer log.Trace(dir, "dir=%q", dir)("entries=%v, err=%v", &entries, &err)
    c, err := f.getFtpConnection(ctx)
    if err != nil {
    return nil, fmt.Errorf("list: %w", err)
    }
    var listErr error
    var files []*ftp.Entry
    resultchan := make(chan []*ftp.Entry, 1)
    errchan := make(chan error, 1)
    go func() {
    result, err := c.List(f.dirFromStandardPath(path.Join(f.root, dir)))
    f.putFtpConnection(&c, err)
    if err != nil {
    errchan <- err
    return
    }
    resultchan <- result
    }()

    $ rg 'backend/ftp/ftp.go:885' m2.log
    1578890:backend/ftp/ftp.go:885:2: (*Fs).List capturing by ref: c (addr=true assign=false width=8)
    1578891:backend/ftp/ftp.go:885:2: c escapes to heap:
    1578892:backend/ftp/ftp.go:885:2:   flow: {storage for func literal} = &c:
    1578893:backend/ftp/ftp.go:885:2:     from c (captured by a closure) at backend/ftp/ftp.go:896:18
    1578894:backend/ftp/ftp.go:885:2:     from c (reference) at backend/ftp/ftp.go:896:18
    1578952:backend/ftp/ftp.go:885:2: moved to heap: c
    

    In the above code, c, which is moved to heap, can be passed to the goroutine through argument to avoid the pointer object c itself allocated in heap. To avoid c still references underlying object, the code can be changed as follows just like what *pc = nil in putFtpConnection(&c, err) does.

    	go func(c *ftp.ServerCon) {
    		result, err := c.List(f.dirFromStandardPath(path.Join(f.root, dir)))
    		f.putFtpConnection(&c, err)
    		if err != nil {
    			errchan <- err
    			return
    		}
    		resultchan <- result
    	}(c)
        c = nil

    I should have shown the assembly where heap allocation function newobject can be found, but the assembly is too large. I made it. Details are shown as follows.

    assembly of "ftp.(*Fs).List" of code before change. c is allocated in heap
    $ go tool objdump -S rclone > rclone.plan9
    $ rg -A 40 'rclone/backend/ftp.\(\*Fs\).List\(SB\)' rclone.plan9 # only relevant line are extracted here. comments are added.
    8569382:TEXT github.com/rclone/rclone/backend/ftp.(*Fs).List(SB) /home/lqw/mygit/QLStat/repos/github.com/rclone/backend/ftp/ftp.go
    8569383-func (f *Fs) List(ctx context.Context, dir string) (entries fs.DirEntries, err error) {
    8569384-  0x2385f80             4c8da42400ffffff        LEAQ 0xffffff00(SP), R12
    8569385-  0x2385f88             4d3b6610                CMPQ R12, 0x10(R14)
    8569386-  0x2385f8c             0f861d090000            JBE 0x23868af
    8569387-  0x2385f92             55                      PUSHQ BP
    8569388-  0x2385f93             4889e5                  MOVQ SP, BP
    8569389-  0x2385f96             4881ec78010000          SUBQ $0x178, SP
    8569390-        if err != nil {
    8569391-  0x2385f9d             4889842488010000        MOVQ AX, 0x188(SP)
    8569392-  0x2385fa5             4889b424a8010000        MOVQ SI, 0x1a8(SP)
    8569393-  0x2385fad             4889bc24a0010000        MOVQ DI, 0x1a0(SP)
    8569394-  0x2385fb5             48898c2498010000        MOVQ CX, 0x198(SP)
    8569395-  0x2385fbd             48899c2490010000        MOVQ BX, 0x190(SP)
    8569396-        c, err := f.getFtpConnection(ctx)
    8569397-  0x2385fc5             488d0534a1b901          LEAQ type:ymgbKdzc(SB), AX
    8569398-  0x2385fcc             e8cfcb08ff              CALL runtime.newobject(SB)      # `c` pointer object is allocated in heap.
    8569399-  0x2385fd1             4889842470010000        MOVQ AX, 0x170(SP)               # `&c` is stored in 0x170(SP)
    8569400-  0x2385fd9             440f11bc2450010000      MOVUPS X15, 0x150(SP)
    8569401-  0x2385fe2             488b842488010000        MOVQ 0x188(SP), AX
    8569402-  0x2385fea             488b9c2490010000        MOVQ 0x190(SP), BX
    8569403-  0x2385ff2             488b8c2498010000        MOVQ 0x198(SP), CX
    8569404-  0x2385ffa             e861ddffff              CALL github.com/rclone/rclone/backend/ftp.(*Fs).getFtpConnection(SB)   # return value of getFtpConnection is stored in AX
    8569405-  0x2385fff             48899c2450010000        MOVQ BX, 0x150(SP)
    8569406-  0x2386007             48898c2458010000        MOVQ CX, 0x158(SP)
    8569407-  0x238600f             833dfa28c00300          CMPL runtime.writeBarrier(SB), $0x0
    8569408-  0x2386016             750a                    JNE 0x2386022
    8569409-  0x2386018             488b942470010000        MOVQ 0x170(SP), DX              # `&c` moved to DX
    8569410-  0x2386020             eb17                    JMP 0x2386039
    8569411-  0x2386022             e839960fff              CALL local.runtime.gcWriteBarrier2(SB)
    8569412-  0x2386027             498903                  MOVQ AX, 0(R11)
    8569413-  0x238602a             488b942470010000        MOVQ 0x170(SP), DX
    8569414-  0x2386032             4c8b02                  MOVQ 0(DX), R8
    8569415-  0x2386035             4d894308                MOVQ R8, 0x8(R11)
    8569416-  0x2386039             488902                  MOVQ AX, 0(DX)                    # return value of getFtpConnection is stored in `c` which is allocated in heap.
    assembly of "ftp.(*Fs).List" of code after change. c is allocated in stack.
    $ go build; go tool objdump -S rclone > rclone-opt.plan9
    $ rg -A 50 'rclone/backend/ftp.\(\*Fs\).List\(SB\)' rclone-opt.plan9
    8569422-        c, err := f.getFtpConnection(ctx)
    8569423-  0x238604e             48898424d8000000        MOVQ AX, 0xd8(SP) # AX is return value of getFtpConnection and is stored into stack

    Pardon the shameless plug, but I've developed a small linter that handles this issue. I come from the static analysis tool CodeQL with escape analysis extension which combines the escape analysis log and CodeQL database. Based on the extension and the heapvar_should_move.ql, I find these opportunities of optimization. For rclone, there are only 5 locations which seems not hot code.

  5. ncw commented on Jan 6, 2026

    @ncw
    Member

    Every little bit helps :-)

    Thanks for showing the before and after escape analysis - that is great to show it makes a difference.

  6. added a commit that references this issue on Jan 9, 2026
    530a901
  7. added 2 commits that reference this issue on Jan 21, 2026
    3af7cbf
    af47701
  8. added a commit that references this issue on Feb 14, 2026
    d9de6c5
  9. added a commit that references this issue on Jul 20, 2026
    02d57b2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions