簡體   English   中英

性能if(typeof x =='number')?

[英]Performance if (typeof x == 'number')?

我一直在谷歌搜索一段時間,例如'typeof'和'performance',但我還沒有找到一個滿意的答案來解決以下問題。

我正在嘗試使用本地運算符重載為Transcrypt Python到JavaScript編譯器實現復數。 由於我們正在處理動態類型語言,因此無法預測變量中的數據類型。

如果我將x + y轉換為JavaScript,打開運算符重載,它將轉換為例如__add__ (x, y)為了做正確的事情, __add__函數必須檢查xy是否是'普通的'JavaScript編號或者其中一個或兩個都是'復雜'類型,因為這需要特殊操作。

最明顯的方法是測試typeof x == 'number' 然而,來自C / C ++背景,用一個帶有六個字符的字符串來測試相等性似乎是非常低效的,首先必須從內存中檢索它,只有可能添加兩個整數,這對於許多處理器來說,一次解析后,只會有一條指令。

讓我感到驚訝的是,像這樣的檢查建議在互聯網的各個地方作為正常的事情。 有沒有人知道x == 'number'或可能的x === 'number'是以某種方式巧妙地優化,以防止完整的字符串比較。

為了進一步澄清問題,這是我當前使用字符串比較的__add__運算符的代碼。

def __add__ (self, other):
    if __typeof__ (other) == 'number':   # Translates to: if (typeof other == 'number') {
        return complex (self.real + other, self.imag)
    else:   # Other is complex
        return complex (self.real + other.real, self.imag + other.imag)

如果沒有,任何人都可以通過更快的方式暗示我區分數字和任意非數字對象。

謝謝你的提示。 來源現在是:

def __sub__ (self, other):
    if __typeof__ (other, 'number'):
        return complex (self.real - other, self.imag)
    else:
        return complex (self.real - other.real, self.imag - other.imag)

被某某人翻譯:

elif node.func.id == '__typeof__':
    self.emit ('typeof ')
    self.visit (node.args [0])
    self.emit (' === ') # Give JavaScript string interning a chance to avoid char by char comparison
    self.visit (node.args [1])
    return

至:

get __add__ () {return __get__ (this, function (self, other) {
    if (typeof other === 'number') {
        return complex (self.real + other, self.imag);
    }
    else {
        return complex (self.real + other.real, self.imag + other.imag);
    }
});},

這取決於JavaScript引擎。 但是一個類型的typeof obj只能返回一組固定的字符串。 因此,編譯器/引擎可以將類型的typeof obj === 'number'優化為不進行字符串比較的測試,但使用更有效的測試。

if( typeof obj === 'number' )創建的字節代碼V8將是這樣的:

268 S> 0x24110cfe4b0 @   62 : 13 04     LdaImmutableCurrentContextSlot [4]
       0x24110cfe4b2 @   64 : 65 00     TestTypeOf #0
       0x24110cfe4b4 @   66 : 86 16     JumpIfFalse [22] (0x24110cfe4ca @ 88)

所以至少v8實際上有一個自己的命令來測試對象是否屬於某種類型,這不是字符串比較。

我不知道其他引擎是否屬於這種情況,但它們可能會做同樣的事情。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM