我正在编写一个算法,其中效率非常重要。有时我也想通过调用一些“回调”函数来跟踪算法行为。假设我的代码如下所示:
public float myAlgorithm(AlgorithmTracker tracker) {
while (something) { // millions of iterations
doStuff();
if (tracker != null) tracker.incrementIterationCount(); // <--- How to run the if only once?
doOtherStaff();
}
}
Run Code Online (Sandbox Code Playgroud)
如何防止执行 if 语句一百万次?编译器是否看到tracker从未重新分配?如果它在第一次检查时为空,它将始终为空。如果不是,则永远不会。
理想情况下,我想告诉编译器以这种方式构建我的代码,以便如果tracker为 null(在运行时),它将以与以下相同的性能运行
while (something) { // millions of iterations
doStuff();
doOtherStaff();
}
Run Code Online (Sandbox Code Playgroud)
我想到了两个解决方案:
我可以编写两个版本的 myAlgorithm,一个有调用,一个没有调用,但这会导致大量代码重复。
我可以将 AlgorithmTracker 提取到一个界面并创建一个带有空函数的假空跟踪器。不过,我不知道编译器是否会优化调用。
目前,我正在尝试 kotlin 协程,我问自己一个问题:使用协程时是否有显着的性能提升?让我们看一些(理论)例子:
val myUnsortedList = listOf(1, 2, 5, 6, 3, 10, 100)
fun doStuffWithSorted(list: List<Int>) { ... }
// Without coroutine
val sortedList = myUnsortedList.sorted()
doStuffWithSorted(sortedList)
coroutineScope {
launch {
val sortedList = myUnsortedList.sorted()
doStuffWithSorted(sortedList)
}
}
Run Code Online (Sandbox Code Playgroud)
fun doSomeHeavyOperations() { // doing heavy Operations but non blocking }
fun main() { doSomeHeavyOperations() }
//////////////// VERSUS //////////////////////
suspend fun doSomeHeavyOperations() { // doing heavy Operations but non blocking }
suspend fun main() {
coroutineScope {
launch {
doSomeHeavyOperations() …Run Code Online (Sandbox Code Playgroud) 我试图理解多维数组和指针,编写这个小程序来理解这个概念:
#include<stdio.h>
void show(int arr[][2]);
int main()
{
int z[2][2] = { { 1, 2 },
{3, 4 } };
show(z);
}
void show(int arr[][2])
{
printf("value of arr = %d", arr);
printf("\n\nvalue of &arr[0]0] = %d", &arr[0][0]);
}
Run Code Online (Sandbox Code Playgroud)
这个代码片段打印相同的地址是有意义的,但是当我编辑show函数时:
void show(int arr[][2])
{
printf("value of *arr = %d", *arr);
printf("\n\nvalue of arr[0]0] = %d", arr[0][0]);
}
Run Code Online (Sandbox Code Playgroud)
*arr仍然打印相同的地址,而arr [0] [0]按预期打印整数值,我想知道为什么我需要使用**arr来获取int值,如果arr存储它应该是的地址用*arr取消引用,不是吗?
请帮助我很难理解这个概念..提前感谢.
我需要找到飞机的名称,以便所有经过认证的飞行员都可以获得超过60000 的飞机.
查询我写道:
select aname
from employee join certified
on employee.eid=certified.eid
join aircraft
on certified.aid=aircraft.aid
where salary>60000;
Run Code Online (Sandbox Code Playgroud)
但如果有任何飞行员超过60000的薪水,它会返回aname,困难的部分是我需要找到所有飞行员的收入超过60000才会显示aname.
我试图理解sizeof运算符的工作,我遇到了 这个 问题.以下是该问题的代码
#include <stdio.h>
int main() {
int i = 0;
int a[i];
printf("%zu\n",sizeof(a[i++]));
printf("%d\n",i); // Here, print 0 instead of 1
return 0;
}
Run Code Online (Sandbox Code Playgroud)
数组a这里是可变长度但是当它用作sizeof运算符的操作数时,变量i不会递增.
一些评论和答案说这a[i++]不是VLA类型,并建议op应该使用2D VLA来查看副作用(sizeof评估其oprand).
我不清楚为什么a[i++]不符合VLA表达的条件.我认为这与我们可以在传递给一个函数时保留第一个未指定数组的事实有关.
所以问题一般是什么被认为是VLA表达?
return@onClicklistener下面提到的代码做了什么
if (password.isEmpty()) {
Toast.makeText(this@MainActivity, "Missing password", Toast.LENGTH_SHORT).show()
return@OnClickListener
Run Code Online (Sandbox Code Playgroud)