【问题标题】:why this java code takes less space and time compared to cpp为什么这个java代码比cpp占用更少的空间和时间
【发布时间】:2020-11-16 04:59:56
【问题描述】:
class Solution {
public:
    void inorder(TreeNode* root, int low, int high, int& res){
        if(root != nullptr){
            inorder(root->left, low, high, res);
            if(root->val <= high && root->val >= low){
                res += root->val;
            }
            inorder(root->right, low, high, res);
        }
    }
    int rangeSumBST(TreeNode* root, int low, int high) {
        int res=0;
        inorder(root, low, high, res);
        return res;
    }
};

Java:

class Solution {
    int res;
    public void inorder(TreeNode root, int low, int high){
        if(root != null){
            inorder(root.left, low, high);
            if(root.val <= high && root.val >= low){
                res += root.val;
            }
            inorder(root.right, low, high);
        }
    }
    public int rangeSumBST(TreeNode root, int low, int high) {
        res = 0;
        inorder(root, low, high);
        return res;
    }
}

Leetcode 938题,求BST的Range sum [low, high]

我在两种语言中的表现都差不多(我猜,但我是 java 新手),但 java 代码与 cpp 相比如何如此之快?它与指针和引用或站点使用的编译器有关吗?
问候

【问题讨论】:

  • 你是如何编译 C++ 的?你打开优化了吗?你是如何安排时间的?
  • 我在 leetcode 它显示运行时和内存本身休息我不知道你在问什么我还不知道优化和东西
  • 可能是网站被窃听了?
  • 优化是在你花很多时间参加竞争之前学习的好东西。这几乎都是关于优化和知道如何滥用编译器。可能是 JIT 编译器足够聪明,可以找到消除所有工作的方法。除非您非常了解评审系统,否则很难确定到底发生了什么。顶级竞争对手也会这样做。
  • quick-bench.com 花点时间阅读和练习来弄清楚,但时间花得值。可能还有其他一些类似的工具,但这是第一个出现在我脑海中的工具。

标签: java c++ memory runtime


【解决方案1】:

经过一番研究,我发现它与平台本身有关。 Leetcode: Is java faster than C++

根据一条评论“他们从 Java 的基准测试中删除了编译和其他过程运行时。 这意味着对于 C/C++ 解决方案,编译时间计入运行时"
不确定这有多可靠。

【讨论】:

  • 这不是真的。也不考虑 C++ 编译时间。
  • 无论哪种方式,从 Leetcode 的比较性能推广到其他任何东西都是......误导。这就像将苹果与苹果从山上滚下来进行比较 :-) 根据记录,很难在 Java 和 C++ 之间进行有效的“苹果与苹果”比较。
  • 是的,有道理。
猜你喜欢
  • 2016-11-13
  • 1970-01-01
  • 2021-01-24
  • 1970-01-01
  • 1970-01-01
  • 2013-12-03
  • 2013-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多