1

I used to believe that :buffer file is faster than :edit file if file is an existing unchanged buffer. I even created a tiny function for this:

function! myvim#open(file) abort
  let nr = bufnr(a:file)
  if nr != -1
    exec printf('buffer %d', nr)
  else
    exec printf('edit %s', a:file)
  endif
endfunction

I totally forgot why and when I did this.

So, are there any performance difference between :edit and :buffer on existing buffer?

1
  • 1
    First step would be to profile and decide if the difference matters
    – D. Ben Knoble
    Commented Apr 10, 2019 at 17:12

1 Answer 1

2

It's faster as :buf won't reload the file from disk, whereas :edit will, which is different behaviour.

This is why it's slightly slower in some cases. For most purposes, this is not a huge issue, although it can be over NFS connections, or with larger files. The performance should be identical when opening files that are not yet loaded by Vim.

You can test/benchmark this with e.g. testing.vim:

fun! s:mkbuf()
    new
    call setline(1, repeat('a', 1048576))  " 1M
    silent w! test
endfun

fun! Benchmark_Buf() abort
    call s:mkbuf()
    let l:buf = bufnr('')
    close

    for i in range(0, g:bench_n)
        exe printf('buffer %d', l:buf)
        close
    endfor
endfun

fun! Benchmark_Edit() abort
    call s:mkbuf()
    let l:buf = bufname('')
    close

    for i in range(0, g:bench_n)
        exe printf('edit %s', l:buf)
        close
    endfor
endfun

Which gives me:

$ tvim test -b . .
Benchmark_Edit                   0.599s
Benchmark_Buf                    0.027s

That's a difference for 100 000 runs of the above code, so the actual difference for one invocation is about 0.00000006s for a 1M file.

1
  • Thanks. Nice plugin.
    – dedowsdi
    Commented Apr 16, 2019 at 2:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.