why is this code running time different?

46 views
Skip to first unread message

Jeong HyunJun

unread,
Mar 23, 2023, 9:45:48 AM3/23/23
to v8-users
hello, I've seen a performance difference depending on whether or not a variable is used in the loop.

let longString = '';

for (let i=0;i<10000000;i++) {
longString += `${i}`;
}

console.log(longString.length);

let cnt = 0;
const st = Date.now();

for (let i=0;i<longString.length - 1;i++) {
  if (longString[1] === longString[0]) {
  /// if (longString[i] === longString[0]) {
    cnt ++;
  }
}

console.log(Date.now() - st, cnt);

It is twice as slow with longString[i] than with longString[1].
What optimizations are causing these results?
It doesn't seem to have anything to do with ConsString flattening.

Jakob Kummerow

unread,
Mar 23, 2023, 10:11:44 AM3/23/23
to v8-u...@googlegroups.com
`longString[1]` is loop-independent and can hence be hoisted out of the loop. `longString[i]` actually has to be loaded from memory in each iteration.

(I haven't spent the time to check whether that's really what's happening. Using `--print-opt-code`, or `--trace-turbo` and Turbolizer, you can check on your own.)


--
--
v8-users mailing list
v8-u...@googlegroups.com
http://groups.google.com/group/v8-users
---
You received this message because you are subscribed to the Google Groups "v8-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to v8-users+u...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/v8-users/1ad8718f-5f83-44de-b3de-287625646eb8n%40googlegroups.com.

Jeong HyunJun

unread,
Mar 23, 2023, 10:17:31 AM3/23/23
to v8-users
sorry,  longString[i] is faster than longString[1]
i checked with `--print-opt-code`, but it was too hard to see the difference
2023년 3월 23일 목요일 오후 11시 11분 44초 UTC+9에 Jakob Kummerow님이 작성:
Reply all
Reply to author
Forward
0 new messages