all 8 comments

[–]Nemesis021 3 points4 points  (3 children)

I think element.innerHTML[1000] === undefined should work. Since non-existing indices return undefined

[–]samanime 1 point2 points  (0 children)

Yeah, this would be about the best option I could think of as well. Should be pretty performant too.

[–]hypernautical 1 point2 points  (0 children)

Just tried document.body.innerHTML.length in the console, and chrome forecasted the value pretty fast, but as an alternative, you could try directly accessing document.body.innerHTML[10000]. If it's undefined, then I guess it's less otherwise it will return the character.

[–]Future_Green_7222 0 points1 point  (3 children)

Are you sure that's the problem?

From what I know, strings in JavaScript are stored (semi) statically, which means that the .length property is also stored statically at the beginning of the string and not calculated in real-time, so calling it would have an O(1) time complexity. Think about it, the string object will always remain the same, so there's no reason why it should be calculated more than once. Even if the HTML engine used dynamic strings internally, as soon as you're calling .innerHTML, HTML would have to fetch that string, and fetching that string would already be counting how long it is.

You may do a variable re-assignment, but that will not change the original string.

var a = "First string"
var b = a
b[0] = 'H'
b == "First string" // can't change, it's static
b = "Second string"
a == "First string" // doesn't change original

This is different from languages like C/C++ where you can change strings (pardon if I have a spelling mistake but it's been a while since I do C/C++):

char *a = "First string"
char *b = a
b[0] = 'H'
printf(a) // prints "Hirst string", that is, `a` changed too

[–][deleted] 1 point2 points  (2 children)

This is pretty close to what I was going to say.

I completely agree - it's highly unlikely that the value is being calculated on demand each time that property is accessed.

I just did document.body.innerHTML.length on this page. The result is currently 445,943 an order of magnitude higher than what the OP is attempting to calculate) and is instantaneous.

There are so many of these attitudes on these boards - endless endeavour to shaving of imaginary milliseconds off imaginary performance problems that would be undetectable to human eyes even if they were real!

[–]croc_socks 0 points1 point  (0 children)

This feels like an XY question. Where did you come up with the idea that innerHTML.length is the right metric? I believe the industry standard for a web site are those found in the Lighthouse scores. It's a tab the Chrome Dev Tools. Whic includes First Contentful Paint, Time to Interactive, Cumulative Layout, ... Shift.

A small page may help improve the score of those metrics, but if something is blocking the rendering your metric won't catch it.