对象创建和简单表达式求值哪一个更好?

发布于 2024-12-10 04:44:20 字数 1133 浏览 0 评论 0 原文

一点背景知识,我遇到了无法启用断言的情况(询问 此处)并使用像forceassertions 对我来说是不可能的,因为 这个

在开发和测试阶段,断言一直是我们的强大武器,我们不准备放弃它。

既然如此,我想到了两个选择。 第一个,很像 JUnit 的 Assert 类:

Assert.assertTrue(result.financialInfoDTO.getPeriods().size() <= FinancialInfoConstants.NUMBER_OF_VISIBLE_PERIOD);

第二个,尝试模仿 Java 的本机断言关键字行为,我们可以在其中启用或禁用它:

    Assert.assert(new Assertion() {
       public boolean doAssert() { return result.financialInfoDTO.getPeriods().size() <= FinancialInfoConstants.NUMBER_OF_VISIBLE_PERIOD; }
    });

我希望能够奢侈地启用和禁用断言功能,这是我能想到的唯一解决方案是类似后者的东西。我要问的是,考虑到大多数断言是比较集合的大小和比较某种类型的值,我们最好使用第一个选项还是后者?

从更技术的角度来说,哪个更有效率?评估简单表达式或一直在堆中创建新对象?

A little background, I'm hitting a situation where I haven't been able to enable assertions (asked here) and using a great solution like forceassertions is not possible for me because of this.

Assertions have always been a formidable weapon for us during the development and testing phase and we're not prepared to let it go.

That being the case, 2 options came into my mind.
The first, much like JUnit's Assert class:

Assert.assertTrue(result.financialInfoDTO.getPeriods().size() <= FinancialInfoConstants.NUMBER_OF_VISIBLE_PERIOD);

The second, trying to mimic Java's native assert keyword behaviour where we can enable or disable it:

    Assert.assert(new Assertion() {
       public boolean doAssert() { return result.financialInfoDTO.getPeriods().size() <= FinancialInfoConstants.NUMBER_OF_VISIBLE_PERIOD; }
    });

I would like to have the luxury to enable and disable the assertion feature, which only solution I can think of is something like the later. What I am asking is, given most assertion would be comparing the size of collections and comparing values of some sort, would we better off using the first option or the later?

To put it in a more technical context, which is more efficient? evaluating simple expression or creating new objects in the heap all the time?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

半﹌身腐败 2024-12-17 04:44:20

对象实例化通常更昂贵。您可以自己进行基准测试。

Object instantiation is usually more expensive. You can benchmark it yourself.

不气馁 2024-12-17 04:44:20

我将选择选项 1。

  1. 它阻止创建新的匿名类和
    每次通过代码时都会实例化该对象。

  2. 使用第二个选项,您将访问一个对象
    (result) 在断言类之外定义。

  3. 这是第一个原因,您不认为第一个更具可读性吗?

I will choose option 1.

  1. It prevents from the creation of a new anonymous class and the
    instanciation of this object each time you pass through your code.

  2. With the second option you are accessing an object
    (result) defined outside of your assertion class.

  3. That's the first reason, don't you think that first one is more readable?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文