1

hello I'm currently doing some LeetCode exercises and I'm failing to understand why I have a faster runtime on the first code sample than the second on this reverse list problem. the linked list is like so:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     public int val;
 *     public ListNode next;
 *     public ListNode(int val=0, ListNode next=null) {
 *         this.val = val;
 *         this.next = next;
 *     }
 * }
 */

With local function create a new Node and make it the beggining of the list

  • Runtime: 94 ms
  • Memory: 39 MB
public ListNode ReverseList(ListNode head) {
    if(head == null){
        return null;
    }
    
    ListNode AddNodeToBeginning(ListNode source, int val)
    {
        return new ListNode(val, source);
    };

    ListNode res = null;
    while(head != null){
        res = AddNodeToBeginning(res, head.val);
        head = head.next;
    }
    return res;
}        

(without local function)

  • Runtime: 129 ms
  • Memory: 38 MB
public ListNode ReverseList(ListNode head) {
    if(head == null){
        return null;
    }

    ListNode res = null;
    while(head != null){
        res = new ListNode(head.val, res);
        head = head.next;
    }
    return res;
}

My question is does why does using the local function to create a new node always gives me faster runtime

the question is https://leetcode.com/problems/reverse-linked-list/submissions/

Richard
  • 481
  • 1
  • 3
  • 11
  • Please post a sample input linked-list so we can reproduce the behaviour you're seeing. – Dai Aug 21 '22 at 19:19
  • 4
    I would have expected the method in the first example to be inlined, effectively making the examples identical. If there is a significant difference I would suspect either some problem with the measurement, or some compiler artifact. I would suggest testing with benchmark .Net to see if the runtime makes any difference. – JonasH Aug 21 '22 at 19:32
  • the test samples are: [1,2,3,4,5], [1,2] and [] – Richard Aug 21 '22 at 20:07
  • I actually get very slightly slower results using the first version. Have you tested it with BenchmarkDotNet? – Charlieface Mar 16 '23 at 16:11

0 Answers0