Best way to append an element to a list?

39 views
Skip to first unread message

David Storrs

unread,
Nov 16, 2021, 2:05:00 PM11/16/21
to Racket Users
If I want to add an element to the end of an immutable list, is it better to do:

(append current-list (list new-element))
or
(reverse (cons new-element  (reverse current-list)))
or
something else? 

I would imagine it's the first one because that should be a single traversal and link add instead of two traversals and rebuilds, but maybe I'm wrong.

Sage Gerard

unread,
Nov 16, 2021, 2:15:08 PM11/16/21
to racket...@googlegroups.com

I get these timings on x86_64 GNU/Linux using the following profile program.

; A: cpu time: 7444 real time: 7445 gc time: 716                                    
; B: cpu time: 9227 real time: 9228 gc time: 884

(module profile racket/base
  (define target-length #e5e4)

  (define (A current-list new-element)
    (append current-list (list new-element)))

  (define (B current-list new-element)
    (reverse (cons new-element  (reverse current-list))))

  (define (profile function)
    (printf "~a: " (object-name function))
    (time
     (void (for/fold ([l null])
                     ([n (in-range target-length)])
             (function l n)))))

  (profile A)
  (profile B))


--
You received this message because you are subscribed to the Google Groups "Racket Users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to racket-users...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/racket-users/CAE8gKocM4jNCg6xKruYwuwFtuOdbOSwugYcgUND1ZD%3DRB1iA0g%40mail.gmail.com.

David Storrs

unread,
Nov 16, 2021, 2:24:29 PM11/16/21
to Racket Users
Reply all
Reply to author
Forward
0 new messages