Why using stack container is slower?

Wentao Wang :

I 'm trying to solve problem 739, Daily Temperatures on LeetCode. https://leetcode.com/problems/daily-temperatures/

My code used Stack container provided by the JAVA. It takes 60 ms to run. This is my code:

class Solution {
    public int[] dailyTemperatures(int[] T) {
        int[] ret = new int[T.length];
        Stack<Integer> stack = new Stack<Integer>();
        for(int i=0; i < T.length; i++){
            while(!stack.isEmpty() && T[i] > T[stack.peek()]){
                int index = stack.pop();
                ret[index] = i - index;             
            }
            stack.push(i);
        }
        return ret;
    }
}

Here is a code that only takes 6ms to run:

class Solution {
    public int[] dailyTemperatures(int[] T) {

        int[] temperatures = T;
        if(temperatures == null) return null;

        int[] result = new int[temperatures.length];
        int[] stack = new int[temperatures.length];
        int top = 0;
        stack[top] = -1;

        for(int i = 0; i < temperatures.length; i++) {
            while(stack[top] != -1 && temperatures[i] > temperatures[stack[top]]) {
                int index = stack[top--];
                result[index] = i - index;
            }

            stack[++top] = i;
        }

        return result;
    }
}

Why building the stack using an array is faster than using the stack container?

Mureinik :

Java's Stack is a very old class, introduced back in JDK 1.0. It extends Vector, and all it's data manipulation methods are synchronized, creating a very sizeable performance overhead. While it isn't officially deprecated, it's outdated, and you really shouldn't be using it in this day and age. The modern ArrayDeque provides the same functionality without the synchronization overhead.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=135012&siteId=1