我有2个不同版本的strlen,它们应该执行相同的操作,但是我不确定哪个版本会更快,更具可读性或更节能。
//version 1
size_t strlen(const char *str) {
size_t retval;
for(retval = 0; *str != '\0'; str++) retval++;
return retval;
}
//version2
size_t strlen(const char *str) {
const char *s;
for (s = str; *s; ++s);
return(s - str);
}
还是只是将它们翻译成相同的汇编代码?
答案 0 :(得分:0)
函数的时间复杂度均为 private void ConnectToWebSocket() {
URI uri;
try {
uri = new URI("ws://192.168.1.135:9000/");
} catch (URISyntaxException e) {
e.printStackTrace();
return;
}
mWebSocketClient = new WebSocketClient(uri) {
@Override
public void onOpen(ServerHandshake serverHandshake) {
Log.i("Websocket", "Opened");
mWebSocketClient.send("Hello from " + Build.MANUFACTURER + " " + Build.MODEL);
}
@Override
public void onMessage(String s) {
final String message = s;
runOnUiThread(new Runnable() {
@Override
public void run() {
TextView textView = (TextView)findViewById(R.id.edittext_chatbox);
textView.setText(textView.getText() + "\n" + message);
}
});
}
@Override
public void onClose(int i, String s, boolean b) {
Log.i("Websocket", "Closed " + s);
}
@Override
public void onError(Exception e) {
Log.i("Websocket", "Error " + e.getMessage());
}
};
mWebSocketClient.connect();
}
。因此,从理论上讲,按时性能两者都将花费几乎相同的时间来计算。尽管标准O(n)
函数的时间复杂度也是strlen
,但它可能具有更高的效率。
看看this。