Why does creating a new object inside local function results in a faster runtime?

60 Views Asked by At

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/

0

There are 0 best solutions below