我目前与我的第二年JAVA教授有分歧,我希望你们都能帮忙解决:
我们开始的代码是这样的:
public T peek()
{
if (isEmpty())
.........
}
public boolean isEmpty()
{
return topIndex<0;
}
Run Code Online (Sandbox Code Playgroud)
并且她希望我们删除isEmpty()引用并将其代码直接放入if语句中(即将peek方法内容更改为:)
if(topIndex<0).......以"使代码更高效".我认为a)运行时/编译时优化器很可能已经内联,isEmpty() call, b)即使它没有,5-10机器操作在几乎所有情况下都可以忽略不计,并且c)它的坏风格因为它使得程序可读性较差,变化较小.
所以,我想我的问题是:内联逻辑与仅调用方法相比,是否有任何运行时效率?我尝试过简单的分析技术(又名长循环和秒表),但测试尚无定论.
编辑:
谢谢大家的回复!我很感谢你们所有的时间.此外,我感谢那些评论与我的教授争论的实用主义,特别是在没有数据的情况下这样做的人.@Mike Dunlavey我很欣赏你作为前教授的见解以及你对适当编码顺序的建议.@ya_pulser我特别感谢您花时间分享的分析建议和链接.
我试图在字符串中找到一个字符,但我得到了意想不到的结果.我的理解是,找不到它时string::find(char c)返回-1.但是,我得到了一些意想不到的结果.
即使字符串不包含'8',它仍然会返回true.
std::string s = "123456799";
if(s.find('8')<0)
cout << "Not Found" << endl;
else
cout << "Found" << endl;
//Output: Found
Run Code Online (Sandbox Code Playgroud)
但是,在使用时==,代码按预期工作.
std::string s = "123456799";
if(s.find('8')==-1)
cout << "Not Found" << endl;
else
cout << "Found" << endl;
//Output: Not Found
Run Code Online (Sandbox Code Playgroud)